简体   繁体   中英

How to make a macro in Twig?

I use a big piece of code for displaying friends and I use it in several templates, so I wanted to make it a macro, but the syntax is a way unusal and I don't know if there is a way this to be done.

The part of the code, which I want to seperate is:

       {% if(fr.email != null) %}
            <p>
                <span class ="label">Email Address: </span> 
                <a  class="email" href="{{ path('friend_email', {'id': fr.id}) }}">
                    {{ fr.email }}
                </a>
            </p>
        {% endif %}

        {% if(fr.phone != null) %}
            <p>
                <span class="label">Phone: </span>
        {{ fr.phone }}
            </p>
        {% endif %}

and so on for about 10 variables. In another template I use this, but instead of fr.email, fr.phone and so on, I need friend.email, friend.phone...

I tried this but without success:

{% macro display_friend(fr) %}

    {% if({{ fr }}.email != null) %}
            <p>
                <span class ="label">Email Address: </span> 
                <a  class="email" href="{{ path('friend_email', {'id': {{ fr }}.id}) }}">
                    {{ {{ fr }}.email }}
                </a>
            </p>
        {% endif %}

        {% if({{ fr }}.phone != null) %}
            <p>
                <span class="label">Phone: </span>
        {{ {{ fr }}.phone }}
            </p>
        {% endif %}
{% endmacro %}

If necessary, I can use fr.email, fr.phone, fr.* ... in each template, so maybe inheritance will work?

So my question is: is there a way to make this part of code macro and if yes will it be better or inheritance will be better?

In your situation, rather than a using a macro I would just include a twig file, using the with option. For example, you can do:

{% include 'AcmeDemoBundle:Demo:showFriend.html.twig' with {'fr': friend} %}

and showFriend.html.twig will be:

   {% if(fr.email != null) %}
        <p>
            <span class ="label">Email Address: </span> 
            <a  class="email" href="{{ path('friend_email', {'id': fr.id}) }}">
                {{ fr.email }}
            </a>
        </p>
    {% endif %}

    {% if(fr.phone != null) %}
        <p>
            <span class="label">Phone: </span>
    {{ fr.phone }}
        </p>
    {% endif %}

Within the macro you can just use fr.var so

{% if({{ fr }}.email != null) %}

will become

{% if fr.email %}

As you can see, specifying != null is not required (I even doubt if it'll work, it probably should be fr.email not is null )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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