EzDevInfo.com

mustache.php

A Mustache implementation in PHP. {{ mustache }}

PHP Mustache. Implicit iterator: How to get key of current value(numeric php array)

If I have php array like this:

 $a = array (
    99 => 'Something1',
    184 => 'Something2',
 );

And keys present important information - It can be some constant values, ids e.t.c

Then how can I get key of current element from templete. For example:

{{#data}}

{.} - it is current value, but I need key also.

{{/data}}

In our system too much these kind of arrays and it is uncomfortably re-parse them before. What's better solution for this? Thank you very much!


Source: (StackOverflow)

Single/double quotes in ng-init

Let's say we are passing initial data from php to Angular' view by Mustache, and the data is some string that contain quotes, like "Can't delete item". Mustache by default translates the single quote to the ' like:

 ng-init="message='Can't delete item'"

but that causes some kind of Angular parsing problem:

Lexer Error: Unterminated quote at columns ... ['] in expression [message='Can't delete item']

I can't use Mustache' triple curlies because then it will be like:

 ng-init="message='Can't delete item'"

with the same error in output.

Plunk: http://plnkr.co/edit/GCq4gLrD1NxxCvAsjHy9?p=preview

How can we elegantly solve it on Mustache stage?


Source: (StackOverflow)

Advertisements

Is there a way in mustache to render a block if a section is present without iterating?

I have a section with a header that I want to show only if the array is populated, something like this:

<h1> These are the elements in the array </h1>
<ul>
    {{#myArray}}
    <li>{{name}} - {{value}}</li>
    {{/myArray}}
</ul>

How can I render the <h1> only if myArray is populated?

If i put it inside the # section it is rendered once for every element in the array, which is not what i want.

What's the correct way to do this?


Source: (StackOverflow)

Render js template through php using mustache

I am using mustache PHP to render my html files and everything works correctly except in one case. There is a situation where I load an html file through an ajax call following this structure:

PHP - renders -> HTML - javascript appends -> HTML 2nd file

What I would like to do is to get the mustache parameters into the HTML 2nd file, as some data is generated in the initial PHP file and I wouldn't like to make another call to retrieve this data again.

  • Do I need mustache js version for this ?
  • How can I get the data from the PHP in js by using mustache?
  • And how can I get the PHP rendered variables in the HTML 2nd file ?

What I can do is to insert hidden inputs to get the data from them in javascript but I would really like to avoid this practice. I don't like this practice as user can easily modify the inputs.

Any idea??


Source: (StackOverflow)

How To render Mustache Partial in zf2

I'm using this module https://github.com/widmogrod/zf2-mustache-module

module.config

'strategies' => array(
    'Mustache\View\Strategy'
),

'template_map' => array(
    'My_Main' => __DIR__ . '/../view/main.phtml',
    'My_SideBar'  => __DIR__ . '/../view/partials/templates.mustache',
),

'mustache' => array(
    'partials_loader' => array(__DIR__ . '/../view/partials'),
),

templates.mustache

<div>
<p>Book Title: {{ title }}</p>
</div>

main.phtml view

<?php 
echo $this->partial('My_SideBar', array('title' => 'My partial'));
?>

Output: Book Title : {{ title }}


Source: (StackOverflow)

Can I use a Mustache var in a partial name?

I currently use a template for multiple pages (basic.mustache) and everything work great, but I want to add different boxes (box1.mustache, box2.mustache) in a sidebar depending of the page.

Basically, I would need to add the mustache templates in the object parsed by the template.

{
  title: "My page tile",
  content: ...
  sidebar: [
    "box1.mustache",
    "box2.mustache"
  ]
}

but how can I do something equivalent to this in the main template (basic.mustache) ?

{{#sidebar}}
  {{>.}}
{{/sidebar}}

Source: (StackOverflow)

How make logical if and else with a parameter value in mustache

How make logical if and else with a parameter value in mustache ? like :

if ($a == "yes") 
  action
else
  action

or like,

if ($a == "yes") 
  action
else if ($a == "maybe") 
else
  action

Source: (StackOverflow)

How to access current context in php mustache as a function?

Right now I have something like this in my mustache template:

{{#render}}{{widget}}{{/render}}

And I have a viewModel which contains this code:

public function render() {
    $View = $this->_View;
    return function($widgetName, Mustache_LambdaHelper $helper) use (&$View) {
        $widget = $helper->render($widgetName);
        return $helper->render($View->mustache->getPartialsLoader()->load("$widget.view"));
    };
}

I think you can see what I am trying to do here. I am trying to render a partial who's name is contained inside the widget-key of the current context.

Now the thing is, I really don't like the format I'm using in the template. I would prefer if I could write something like this:

{{renderWidget}}

then I would need to be able to access the current context directly in some way.

public function renderWidget() {
    return function($context) {
        return $helper->render($View->mustache->getPartialsLoader()->load("$context[widget].view"));
    }
}

Can anybody tell me if that is possible in one way or another?


Source: (StackOverflow)

How to use function wrapper in mustache.php?

I'm starting to work with Mustache on PHP and I don't manage to make wrapper functions to work as debt.

I have this template

{{#skill_level}}
  <span class="stars">
    {{#stars}}
      {{skill_level}} 
    {{/stars}}                        
  </span>
{{/skill_level}}

And I have this data

$data = new StdClass;
$data->skill_level = 3;
$data->stars = function($level) {
  $aux = "";
  $l = intVal($level);
  for ($i = 0; $i < $l; $i++) {
    $aux .= "+";
  }
  for ($i = $l; $i < 5; $i++) {
    $aux .= ".";
  }
  return $aux;
};

I render m.render($tenplate, $data); and I would like to obtain something like:

<span class="stars">
    +++..                        
</span>

But it doesn't work.

I get

<span class="stars">
    .....                        
</span>

Because Mustache is passing "{{skill_level}}"to my function instead of value 3.

Furthermore if I change the template a put backspaces in the mustache labels:

{{ #skill_level }}
  <span class="stars">
    {{ #stars }}
      {{ skill_level }} 
    {{ /stars }}                        
  </span>
{{ /skill_level }}

Then {{ skill_level }} is processed but it isn't sent to {{ #starts }}, the render obtained is

<span class="stars">
    3                        
</span>

So, does anybody know what I'm doing wrong? How should I wrote the template to make it works? Any advice or experience are welcome. Thanks.


Source: (StackOverflow)

working with php and javascript templates

Currently I am use the slim framework to serve html templates to the browser. After the view is loaded the application retrieves some information from a RESTful API and uses handlebars.js to populate various aspects of the DOM.

I would like to use a php template system such as mustache.php or twig to handle some very basic template needs when the html template is being served. However, being handlebars.js uses the same syntax as mustache.php and twig I am having some major conflicts when it comes time to populate the DOM with the information retrieved from the API.

The only solution I have at the moment is to do a str_replace() on the html template instead of using one of the above php templating solutions.

Is there a way I can use one of the php templating solutions and handlebars.js without conflicts?


Source: (StackOverflow)

How to show specific value from array with mustache?

I have an array like:

Array
(
    [0] => Array
        (
            [title] => Title 1
            [value] => Value 1
            [id] => 1428735262
        )

    [1] => Array
        (
            [title] => Title 2
            [value] => Value 2
            [id] => 2428735262
        )

    [2] => Array
        (
            [title] => Title 3
            [value] => Value 3
            [id] => 3428735262
        )

)

With mustache I am able to iterate overall of them using:

{{#values}}
    <h1>{{title}}</h1>
    {{{value}}}
{{/values}}

But what if I only want to show specific value, for example only second element of the array (one with Title 2)?

I tried like:

{{#values}}
{{#2428735262}}
    <h1>{{title}}</h1>
    {{{value}}}
{{/2428735262}}
{{/values}}

and:

{{#values.2428735262}}
    <h1>{{title}}</h1>
    {{{value}}}
{{/values.2428735262}}

But none worked. Does anyone know how to get specific item from array ?

PS. I am using PHP version of mustache. Thanks


Source: (StackOverflow)

how to limit iterations in mustache

I have this mustache template:

{{#pages}}
  <ul class="nav navbar-nav">
    <li><a rel='nofollow' href="page/{{slug}}.html">{{title}}</a></li>
  </ul>
{{/pages}}

Now there are more than 50 pages but I want to be able to show only 10 pages. How to do that in mustache eg limiting the iterations to specific number something like:

{{#pages:10}} <-- 10 added here as example
  <ul class="nav navbar-nav">
    <li><a rel='nofollow' href="page/{{slug}}.html">{{title}}</a></li>
  </ul>
{{/pages}}

I searched the documentation but could not find the solution.

Thanks for the help


Source: (StackOverflow)

looping through two dimensional array and passing to mustache template

so I am just getting started using mustache.php and I am stuck trying to loop though a two dimensional array. I have an array that looks like this...

 $FeedArray = array(3) { [0]=> array(3) { ["entity"]=> string(10) "mail" 
                                          ["time"]=> string(19) "2015-02-05 05:10:26"
                                          ["title"]=> string(0) "what's up?" }         
                         [1]=> array(3) { ["entity"]=> string(5) "event" 
                                          ["time"]=> string(19) "2015-02-05 03:16:54"
                                          ["title"]=> string(15) "asfasggasdgasdg"  } 
                         [2]=> array(3) { ["entity"]=> string(10) "mail"
                                          ["time"]=> string(19) "2015-01-11 14:24:08"
                                          ["title"]=> string(24) "lunch?" } }

I am trying to loop though it like this:

$eventTemplate = file_get_contents('templates/GroupPageEvent.mustache');
$postTemplate = file_get_contents('templates/GroupPagePost.mustache');

       foreach ($FeedArray as $entity => $row){

              if ($row['entity_type']=='mail'){
                     echo $m->render($postTemplate, $entity);
              }

              if ($row['entity_type']=='event'){
                     echo $m->render($eventTemplate, $entity); 
              }

       }

I know my templates are working well and all. Just am not passing in the subarray($entity) properly, and all the outputted templates are empty.

The if $row['entity_type'}==? is reading properly as well.

Any Help appreciated.


Source: (StackOverflow)

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 rel='nofollow' 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 rel='nofollow' href="#">about</a></li><li><a rel='nofollow' href="#">home</a></li></ul>

Instead of the expected result:

  • about
  • home

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!


Source: (StackOverflow)

Rendering Mustache Block with external templates

I'm using Mustache 2.7.0 and trying to play with Blocks pragma for the first time.

Basically, I call basic.mustache

{{< layout }}
{{$ title}}{{page.meta.name}}{{/ title}}
{{/ layout }}

calling the block layout.mustache

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <h1>{{$ title}}test{{/ title}}</h1>
    </body>
</html>

I see the value of page.meta.name appear on the page, but not the tags written in layout.mustache.
Anyone have an idea why?

PHP

$mustache = new Mustache_Engine(array(
    'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS],
    'loader' => new Mustache_Loader_FilesystemLoader('htdocs/templates'),
    'partials_loader' => new Mustache_Loader_FilesystemLoader('htdocs/templates/partials/')
));

$tpl = $mustache->loadTemplate('basic');
echo $tpl->render( $this );

Source: (StackOverflow)