General developer forum

Retrieving image url from theme settings

 
Picture of Jay Darnell
Retrieving image url from theme settings
 

Hello everyone, I'm pretty new to Moodle so please be patient if this is a commonly known thing. I've been reading through theming documentation, researching themes that ship with core and searching online for the last couple days and cannot figure out how to do this. All I want to do is take the file uploaded into a theme setting, get the url for it and use that url for an image in one of my mustache templates. 

I have a theme setting called header logo inside my theme: USWDS (a child theme of Boost)

Inside /theme/uswds/lang/en/theme_uswds.php I have:

$string['headerlogo'] = 'Header logo';
$string['headerlogo_desc'] = 'Upload a file to be displayed as the site logo in the header';


Inside /theme/uswds/settings.php I have:

// Header logo setting.
$name='theme_uswds/headerlogo';
$title = get_string('headerlogo', 'theme_uswds');
$description = get_string('headerlogo_desc', 'theme_uswds');
$setting = new admin_setting_configstoredfile($name, $title, $description, 'headerlogo');
$setting->set_updatedcallback('theme_reset_all_caches');
$page->add($setting);


Inside /theme/uswds/config.php I have: (This is my first layout so I only have the one right now)

$THEME->layouts = [
    // Standard layout with blocks, this is recommended for most pages with general information.
    'standard' => array(
        'file' => 'uswds.php',
        'regions' => array('side-pre'),
        'defaultregion' => 'side-pre',
    ),
    // Server administration scripts.
    'admin' => array(
        'file' => 'uswds.php',
        'regions' => array('side-pre'),
        'defaultregion' => 'side-pre',
    ),
];


Inside /theme/uswds/classes/core_renderer.php I have: (modeling this after a function call by the same name in the clean theme: /theme/clean/classes/core_renderer.php)

<?php
class theme_uswds_core_renderer extends theme_boost\output\core_renderer {
    /**
     * Return the theme logo URL, else the site's logo URL, if any.
     *
     * Note that maximum sizes are not applied to the theme logo.
     *
     * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
     * @param int $maxheight The maximum height, or null when the maximum height does not matter.
     * @return moodle_url|false
     */
    public function get_logo_url($maxwidth = null, $maxheight = 100) {
        global $CFG;
        if (!empty($this->page->theme->settings->headerlogo)) {
            $url = $this->page->theme->setting_file_url('headerlogo', 'headerlogo');
            // Get a URL suitable for moodle_url.
            $relativebaseurl = preg_replace('|^https?://|i', '//', $CFG->wwwroot);
            $url = str_replace($relativebaseurl, '', $url);
            return new moodle_url($url);
        }
        return parent::get_logo_url($maxwidth, $maxheight);
    }
}


Inside /theme/uswds/layout/uswds.php I have: (a copy of columns2.php from Boost I'm manipulating)

<?php
/**
 * A two column layout for the uswds theme.
 *
 * @package   theme_uswds
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
defined('MOODLE_INTERNAL') || die();
user_preference_allow_ajax_update('drawer-open-nav', PARAM_ALPHA);
require_once($CFG->libdir . '/behat/lib.php');
if (isloggedin()) {
    $navdraweropen = (get_user_preferences('drawer-open-nav', 'true') == 'true');
} else {
    $navdraweropen = false;
}
$extraclasses = [];
if ($navdraweropen) {
    $extraclasses[] = 'drawer-open-left';
}
$bodyattributes = $OUTPUT->body_attributes($extraclasses);
$blockshtml = $OUTPUT->blocks('side-pre');
$hasblocks = strpos($blockshtml, 'data-block=') !== false;
$regionmainsettingsmenu = $OUTPUT->region_main_settings_menu();
// Get necessary theme settings.
$govbanner = get_config('theme_uswds', 'govbanner');
$logo = $OUTPUT->get_logo_url(null, 100);
$templatecontext = [
    'sitename' => format_string($SITE->shortname, true, ['context' => context_course::instance(SITEID), "escape" => false]),
    'output' => $OUTPUT,
    'header_logotext' => get_string('header_logotext', 'theme_uswds'),
    'logo' => $logo,
    'sidepreblocks' => $blockshtml,
    'hasblocks' => $hasblocks,
    'bodyattributes' => $bodyattributes,
    'navdraweropen' => $navdraweropen,
    'regionmainsettingsmenu' => $regionmainsettingsmenu,
    'hasregionmainsettingsmenu' => !empty($regionmainsettingsmenu)
];
$templatecontext['flatnavigation'] = $PAGE->flatnav;
echo $OUTPUT->render_from_template('theme_uswds/uswds', $templatecontext);


Lastly, in my /theme/uswds/templates/uswds.mustache file I have a simple img tag with the src equal to {{{ logo }}}. It doesn't work. What am I doing wrong? The example in the clean theme sets the img url as a background for a div but its the same url format. Mine worked once and then stopped working and I have no idea how I broke it.

When uploaded to the clean theme's logo field the url for the image file is as follows:

http://lincscourses3.localtest.me/pluginfile.php/1/theme_clean/logo/-1/logo.png

When uploaded to my uswds theme's logo field the url for the image file is as follows:
http://lincscourses3.localtest.me/pluginfile.php/1/theme_uswds/headerlogo/-1/logo.png

I am completely lost as to what I am doing wrong and would appreciate any guidance you fine folks can provide. If I'm making this too difficult and there is an easier way I'm all ears.




 
Average of ratings: -
Picture of Jay Darnell
Re: Retrieving image url from theme settings
 

Attaching a screenshot of the error I receive when I try to access the generated file URL directly


 
Average of ratings: -
Picture of Jay Darnell
Re: Retrieving image url from theme settings
 

For anyone who runs into this same issue I figured out what was missing. I needed the following function in my theme's lib.php file: (copied from the clean theme and modified with the names of the theme settings for my image uploads)

/**
 * Serves any files associated with the theme settings.
 *
 * @param stdClass $course
 * @param stdClass $cm
 * @param context $context
 * @param string $filearea
 * @param array $args
 * @param bool $forcedownload
 * @param array $options
 * @return bool
 */
function theme_uswds_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options = array()) {
    if ($context->contextlevel == CONTEXT_SYSTEM and ($filearea === 'headerlogo' || $filearea === 'agencylogo')) {
        $theme = theme_config::load('uswds');
        // By default, theme files must be cache-able by both browsers and proxies.
        if (!array_key_exists('cacheability', $options)) {
            $options['cacheability'] = 'public';
        }
        return $theme->setting_file_serve($filearea, $args, $forcedownload, $options);
    } else {
        send_file_not_found();
    }
}


Some useful documentation which initially made me realize I was probably missing a function call or something of that nature:
https://docs.moodle.org/dev/File_API#Serving_files_to_users




 
Average of ratings: Useful (2)