Question

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?

Was it helpful?

Solution

The quickest way to handle this is to change the Mustache delimiters in your server-side template. Something like this:

{{=<% %>=}}
<html>
<head>
  <title><% title %></title>
  <script type="text/x-handlebars-template" id="mytemplate">
    {{# stuff }}{{ otherstuff }}{{/ stuff }}
  </script>
</head>
<body>
  <h1><% title %></h1>
</body>
</html>

That way the <% type delimiters are used by Mustache.php, and the {{ type delimiters are ignored, ensuring they'll be around for use by Handlebars.js.

You can also change delimiters immediately around your Handlebars templates, if you want to keep using Mustaches for your regular delimiters:

<html>
<head>
  <title>{{ title }}</title>
  {{=<% %>=}}
  <script type="text/template" id="mytemplate">
    {{# stuff }}{{ otherstuff }}{{/ stuff }}
  </script>
  <%={{ }}=%>
</head>
<body>
  <h1>{{ title }}</h1>
</body>
</html>

If you move your handlebars templates into a partial:

{{=<% %>=}}
<script type="text/template" id="mytemplate">
  {{# stuff }}{{ otherstuff }}{{/ stuff }}
</script>

... the delimiter change will only apply while inside that partial. Then you can do this:

<html>
<head>
  <title>{{ title }}</title>
  {{> handlebars_templates }}
</head>
<body>
  <h1>{{ title }}</h1>
</body>
</html>

I'd recommend going this route, as it's the most maintainable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top