On Mon, Jun 3, 2013 at 5:36 AM, Daniele Procida <dani...@vurt.org> wrote:

> The for ... empty pattern in templates is common and useful: <
> https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for-empty>
>
> But this is another common pattern:
>
> {% if my_bonnet.bees %}
>     <ul>
>         {% for bee in my_bonnet.bees %}
>             <li>{{ bee }}
>             ...
>
> In other words, we have to check first for items in the iterable before
> creating a <ul> or whatever other furniture to put them in.
>
> The problem here is that my_bonnet.bees gets asked for twice, and it could
> be my.bonnet(), some very expensive function.
>
> One solution is to put everything inside:
>
> {% with my_bonnet.bees as bees %}
>
> but now:
>
> * we've used up a precious level of indentation
> * we've introduced a new variable in the templates to worry about
> * it just feels a bit fussy
>
> Is this enough of an issue to make it worthwhile implementing some other
> approach in the template system?
>
> This specific use case (i.e., the empty UL/OL) has bothered me in the past
as well. However, I'm not sure I see an elegant way to.

I'm open to suggestions, but the only way I can see around the problem is
to put an extra argument on the {% for %} that allows for extra 'wrapper'
content "if not empty" - something like:

{% for bee in my_bonnet.bees pre="<ul class='beelist'>" post="</ul>"%}
    <li>{{ bee }}<li>
{% empty %}
<span>No bees in your bonnet.</span>
{% endfor %}

But I'm really not sure I like the syntax combining markup into tags
arguments. Alternatively, add new sub tags to {% for %}:

{% for bee in my_bonnet.bees %}
{% pre %}
<ul class='bee list'>
{% body %}
    <li>{{ bee }}<li>
{% post %}
</ul>
{% empty %}
<span>No bees in your bonnet.</span>
{% endfor %}

but that's starting to get verbose, and leaves ambiguous what to do with
content appearing between the opening {% for %} and the {% pre %}

Any other syntax I can think of requires introducing another indentation
level. Have you got a specific suggestion for how to address this?

Russ %-)

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-developers+unsubscr...@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.
Visit this group at http://groups.google.com/group/django-developers?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to