开发者

Django html for, if etc

I'm trying to do a simple for loop on my data in djnago-python.

I want to iterate over a list and check if some element x has a specific field value. If so, i want to show a remove option, and if not to show an add option.

It supposed to look like this in a normal language:

flag = false
for x in list:
    if x.game == KNOWN_GAME:
        <show remove link>
        flag = true
        break
endfor
if flag == fals开发者_运维百科e:
    <show add link>

The problem is I don't find the right way to do that: there is no break, no variables to create (the flag) and I don't know how to use loop.last for it.

Any suggestions or some place I can find this tags I want?

EDIT I'm having a trouble to use the view stuff. My KNOWN_GAME is coming from the html page (from some for loop). Do I have some way to pass it from the html to the function in the view?


Django's answer to a lot of things you can't do in the template is to do it in the view.

Generally speaking any complex logic should be done in the view. Django doesn't even support variable declaration in the way you use flag=True. We have the with tag but the variable it defines must be used within the definition block.

View

show_remove_link = False
if any(filter(lambda x: x.game == KNOWN_GAME, my_list)):
    show_remove_link = True

return render_to_response("mytemplate.html", {'show_remove_link': show_remove_link})

Template

{% if show_remove_link %}
    Show Remove Link
{% else %}
    Show Add Link
{% endif %}


I think a better solution to this would be to add that logic into your view. Then pass the resulting flag variable to your template. That's how I'd approach it anyway.


This is logic that is supposed to happen in the python view:

games = [x.game for x in x_list]
game_known = KNOWN_GAME in games
return render(request, 'my_template.html', {'game_known': game_known, ...})

And in the template you have:

{% if game_known %}
    <show remove link>
{% else %}
    <show remove link>
{% endif %}


It'd be better to move this logic into the view, as @Yuji and @Bryan suggest.

Alternatively, if you really want to achieve this in your template, you can write your own custom template tag. Please, refer documentation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜