如何在Twig模板中包含Handlebars.js?

3

我正在使用Twig和Handlebars.js,但是遇到了冲突。我找到了两种解决方案。这两种方法哪一种被认为更合适?或者有没有第三种更合适的方法?如果使用我的Option 1,是否有任何建议的命名标准来将handlebars模板与twig模板关联?

Option 1使用Twig源代码

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>

选项2:使用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 %}
1个回答

5
我不知道是否有普遍偏好,但对我来说两者都可以。当只有少量Handlebars代码时,我更喜欢选项2;在其他情况下(有大量Handlebars代码),我会选择选项1。我会将Handlebars文件(选项1)放入名为handlebars/的文件夹中,这样你就有了handlebars/template1.html等。
另一个选项是使用变量表达式输出变量分隔符({{}},如有关转义的文档部分所述)或整个Handlebars表达式:
{% 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 %}

这很方便,如果您只输出几个Handlebars变量,那么这将比使用单独的文件或使用verbatim标记更加简洁。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接