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

Тел: +7 965 3737 888

543

Просмотров

2

Ответов

IfValueTag

<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
file_2310.py(2.7Кб)
None

Ответы (2):

Ответadurdin:29.03.2007
Ответ полезен? Да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.

Ответmawimawi:22.03.2007
Ответ полезен? Да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"):
    [...]
register.tag('ifnotvalue'...)

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