Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manage and include Handlebars.js files with symfony 2.1 and Assetic

I want to exclude my handlebars.js template from my twig files.

So I created a new directory in the public folder named hbs where I placed all my handlebar templates. How do I tell assetic to render those templates and wrap it with the script tag?

like image 891
Johannes Klauß Avatar asked Mar 25 '13 11:03

Johannes Klauß


1 Answers

You need AsseticBundle 2.1.2 or later. Besides that, you need to do three things:

  1. Install the handlebars compiler
  2. Configure an assetic filter to compile your handlebars templates
  3. Include the templates in your twig template.

Installing the compiler

Follow the instructions on the handlebars website. Or, shorter:

npm install handlebars -g

Configuring the filter

Add this to your config file:

assetic:
    filters:
        handlebars:
             apply_to: "\.handlebars$"

This will tell assetic to apply the handlebars filter to all files ending in ".handlebars", effectively turning them into a compiled handlebars template. You can adjust the setting to whatever ending you prefer.

You may need to tell assetic where your handlebars compiler resides if it isn't in the default location (/usr/bin/handlebars). Use the "bin" setting of the handlebars filter for that. For example, if you have installed it in a subdirectory of your project (by using npm without the -g option), your config might look like this:

assetic:
    filters:
        handlebars:
             apply_to: "\.handlebars$"
             bin: node_modules/handlebars/bin/handlebars

Reference in Twig template

Add a new reference in your twig template similar to how you would include javascript files:

{% javascripts
    '@MyBundle/Resources/public/hbs/*.handlebars'

        output='assets/my-handlebars-templates.js'
        %}
    <script type="text/javascript" src="{{ asset_url }}"></script>  
{% endjavascripts %}

Then you can use the templates in your project. They are stored in Handlebars.templates[templatename] with "template-name" being the filename of your template excluding ".handlebars".

Hope that helps...

like image 197
Florian Sander Avatar answered Oct 16 '22 08:10

Florian Sander