1

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?

4

2 回答 2

4

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 %}
于 2012-09-14T13:42:42.540 回答
1

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 )

于 2012-09-14T13:34:55.400 回答