简体   繁体   English

外部文件中的Twig宏

[英]Twig macro in external file

I have three pages that uses the same macro. 我有三个使用相同宏的页面。 I put the same portion of code in the top of all three pages. 我将相同的代码部分放在所有三个页面的顶部。 Can I put this macro in external file and reuse it? 我可以将此宏放在外部文件中并重新使用吗?

Here the macro: 这里是宏:

{% macro generateMenu(item) %}
    <li>
        <h4>
            <a class="{{ item.class }}" href="{{ item.link }}">
                {{ item.label }}
            </a>
        </h4>
    </li>
{% endmacro %}

Calling the macro: 调用宏:

<ul class="">
    {% for item in Menu %}
        {{ _self.generateMenu(item) }}
    {% endfor %}
</ul>

In fact, there are some variations, I will use some parameters. 实际上,有一些变化,我将使用一些参数。 But the focus is: I want to put this macro in a external file to reuse code. 但是重点是:我想将此宏放在外部文件中以重用代码。

As documentation states: http://twig.sensiolabs.org/doc/tags/import.html 如文档所述: http : //twig.sensiolabs.org/doc/tags/import.html

Define macro in external file and import it in each of your files that use it: 在外部文件中定义宏,并将其导入使用它的每个文件中:

{% import 'external.file.here' as something %}

{{ something.macro_in_that_file(some, params) }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM