Manage and include Handlebars.js files with symfony 2.1 and Assetic
Asked Answered
D

2

6

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?

Deepseated answered 25/3, 2013 at 11:53 Comment(0)
C
9

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...

Ceiling answered 19/4, 2013 at 21:46 Comment(1)
If your node.js executable is in a different location than /usr/bin/node (for example in /usr/local/bin/node if you installed it on Mac OS X via the offical installer), you need to add node:/path/to/node to the handlebars assetic filter configuration.Paintbrush
S
0

You may put right path to handlebars in bin. Following worked for me.

assetic:
    filters:
        handlebars:
            apply_to: "\.handlebars"
            bin: /usr/local/bin/handlebars

Get the right location of handlebars using

which handlebars
Slipover answered 26/11, 2013 at 12:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.