phphtmlcodeignitermustache.php

Dynamic Navigation with Mustache Templating


I have created a template with mustache.php and am wanting to dynamically create my navigation based on files within a single folder. I am using codeigniter for this project.

I have a function that fetches the files and turns them into links, this function is called create_front_navigation()

public function create_front_navigation()
{
    $map = directory_map(APPPATH.'views/front/', 1);

    $files = '<ul>';

    foreach($map as $map)
    {
        $files = $files.'<li><a href="#">'.str_replace('.php', '', $map).'</a></li>';
    }

    $files = $files.'</ul>';

    return $files;
}

That function is called from my function that gathers and creates my partials or mustache translations, called create_partials.

public function create_partials()
{
    $partials = array(

        'navigation' => $this->create_front_navigation(),
        'site' => 'SaleBolt',
        'firstname' => 'John',
        'visitorNumber' => '6',

    );

    return $partials;
}

All that information is then called from the function that actually turns the mustache tags into actual words. This function is simply called, render().

public function render($template)
{
    $template = $this->mustache->loadTemplate($template);

    $page = $template->render($this->create_partials());

    echo $page;
}

My issue is this, Instead of rendering the "navigation" as an actual unordered list. Mustache is simply rendering it as text.

So in my browser, I am seeing this:

<ul><li><a href="#">about</a></li><li><a href="#">home</a></li></ul>

Instead of the expected result:

What am I doing wrong here? Does Mustache provide a better way of doing something like this? I am very very new to Mustache and have taken several tutorials just to get this far. Thank you for your help in advance!


Solution

  • By default, Mustache implementations escape HTML. (They do this to protect you against malicious user-submitted content.) You must use a separate variable syntax to unescape a string containing HTML.

    See Mustache Tags in the bobthecow/mustache.php documentation:

    All variables are HTML escaped by default. If you want to return unescaped HTML, use the triple mustache: {{{ name }}}.

    You can also use & to unescape a variable: {{& name }}. This may be useful when changing delimiters.

    You haven't posted the template you're using, but you need to modify the variable that contains the HTML (e.g., {{ navigation }} should be {{{ navigation }}}).