Задать вопрос

Тел: +7 965 3737 888






<p>Don't repeat yourself: when you wish to have a block of html with a variable value, but only if the variable is set, you can do this:</p>
{% ifvalue company.contact.email as email %}
  &lt;h3&gt;Email address&lt;/h3&gt;
  &lt;a href='mailto:{{ email }}'&gt;{{ email }}&lt;/a&gt;
{% endifvalue %}

<p>Instead of this:</p>
{% if company.contact.email %}
  &lt;h3&gt;Email address&lt;/h3&gt;
  &lt;a href='mailto:{{ company.contact.email }}'&gt;{{ company.contact.email }}&lt;/a&gt;
{% endifvalue %}

<p>The tags ifvalue and ifnotvalue are provided by this snippet.</p>
<p>If you don't specify as somename, then the variable's value will be assigned to the name "value".</p>

Вопрос полезен? Да0/Нет0

Ответы (2):

Ответ полезен? Да0/Нет0

@limodou, SmileyChris -- I'd still be using this tag even if I had the expr or with tags; I don't want to have to do:

{% with someobject.somevalue as value %}{% if value %}<p><a href='/'>{{ value }}</a></p>{% endif %}{% endwith %}

The assignation of the value to another name is an adjunct to the purpose of entirely omitting the html elements if their contained value is empty.


I've just updated the snippet to support filters; in my templatetag naïveté I'd not known how to this initially.

Ответ полезен? Да0/Нет0

I like it a lot! (but it is unneccessarily python2.4-code and incompatible with python2.3)

you might consider not using decorators, but instead the old python style:

def ifnotvalue(parser, token, name="value"):

maybe in this case it might even be possible to add your tag to the core? (wishful thinking, of course)