Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include Handlebars.js in Twig template?

I am using both Twig and Handlebars.js, and was running into conflicts. I found two solutions. Is one considered more proper than the other, or is there a third more appropriate solution? If my Option 1 is used, are there any recommended naming standards to associate the handlebars template to the twig template?

Option 1 using twig source

my_twig_template1.html

{% block content %}
<h1>Hello</h1>
<p>{{ someTwigPhpVar }}</p>
{{ source('my_handlebars_template1.html') }}
{% endblock %}

my_handlebars_template1.html

<script id="my-handlebars-item-1" type="text/x-handlebars-template">
    {{someHandleBarVariable}}
</script>

<script id="my-handlebars-item-2" type="text/x-handlebars-template">
    {{someHandleBarVariable}}
</script>

Option 2 using twig verbatim

my_twig_template2.html

{% block content %}
<h1>Hello</h1>
<p>{{ someTwigPhpVar }}</p>

{% verbatim %}

<script id="my-handlebars-item-1" type="text/x-handlebars-template">
    {{someHandleBarVariable}}
</script>

<script id="my-handlebars-item-2" type="text/x-handlebars-template">
    {{someHandleBarVariable}}
</script>

{% endverbatim %}

{% endblock %}
like image 966
user1032531 Avatar asked Dec 14 '25 18:12

user1032531


1 Answers

I don't know if there's a general preference, but both look okay to me. I would prefer option 2 when there's just a few lines of Handlebars code and option 1 in other cases (with big sections of Handlebars code). I would put the Handlebars files (option 1) into a folder called handlebars/, so that you have handlebars/template1.html etc.

Another option is to use a variable expression to output the variable delimiters ({{ and }}, as described in the documentation section about escaping) or the whole Handlebars expression:

{% block content %}
    <h1>Hello</h1>
    <p>{{ someTwigPhpVar }}</p>

    <script id="my-handlebars-item-1" type="text/x-handlebars-template">
        {{ '{{' }} someHandleBarVariable {{ '}}' }}
    </script>

    <script id="my-handlebars-item-2" type="text/x-handlebars-template">
        {{ '{{someHandleBarVariable}}' }}
    </script>
{% endblock %}

This is handy if you are outputting just a couple of Handlebars variables so this will be more concise than having a separate file or using the verbatim tag.

like image 50
Matias Kinnunen Avatar answered Dec 16 '25 09:12

Matias Kinnunen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!