在 django 模板中使用相同的块根据变量显示不同的信息
嘿,堆栈溢出先生! 我试图根据一个简单的 int 变量“选择”在同一个块中显示不同的信息。我计划这样做的方式将类似于下面的代码:
{% extends "index.html"%}
{%block head%}
<p><h1>Welcome to Piss && ink {{user}}</h1></p>
{%endblock head%}
{%block one%}
<p>The temperature in {{city}} is {{temperature}}° </p>
{%endblock one%}
{%if choice1 == 2 %}
{%block two%}
<p>The temperature in {{city}} is {{temperature}}° </p>
{%endblock two%}
{% endif %}
{%comment%}
{%if choice1 == 2 %}
{%block two%}
<p>The temperature in {{city}} is {{temperature}}° </p>
{%endblock%}
{% endif %}
{%endcomment%}
{%block two%}
<form method="post">
{%csrf_token%}
{% if new_event %}
<b><p>{{new_event}}</p></b>
{% endif %}
{%endblock%}
现在,我遇到的问题是模板不喜欢模板中有两个同名的块。由于某种原因,它似乎并不关心检查 {% block %}
应该去哪里的 {% if %}
语句。我认为 {% if %}
语句只会根据其参数执行其内部的内容,但它似乎并没有这样做。它显示 {% if %}
内的所有内容,无论“choice1”也相等:( 有谁知道我如何解决这个问题?谢谢
Hey Mr. Stack overflow!
I am trying to have different information display in the same block depending on a variable "choice" which is simply an int. The way I was planning on doing so was going to be something like the bellow code:
{% extends "index.html"%}
{%block head%}
<p><h1>Welcome to Piss && ink {{user}}</h1></p>
{%endblock head%}
{%block one%}
<p>The temperature in {{city}} is {{temperature}}° </p>
{%endblock one%}
{%if choice1 == 2 %}
{%block two%}
<p>The temperature in {{city}} is {{temperature}}° </p>
{%endblock two%}
{% endif %}
{%comment%}
{%if choice1 == 2 %}
{%block two%}
<p>The temperature in {{city}} is {{temperature}}° </p>
{%endblock%}
{% endif %}
{%endcomment%}
{%block two%}
<form method="post">
{%csrf_token%}
{% if new_event %}
<b><p>{{new_event}}</p></b>
{% endif %}
{%endblock%}
Now, the problem I am having is that the template doesn't like that there are two blocks of the same name in the template. For some reason it doesn't seem to care about the {% if %}
statement that is checking where the {% block %}
is supposed to go. I thought that the {% if %}
statement would only execute what was inside itself depending on its parameters but it doesn't seem to be doing that. It displays everything inside the {% if %}
no matter what "choice1" is equal too :( Does anyone have any idea how I might be able to fix this? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将逻辑放在块内,而不是有两个同名的块。
代替:
使用:
Put the logic inside the block instead of having two blocks of the same name.
Instead of:
use:
将 if 放在块内。一个块,两个 if 语句
Put the if inside the block. One block, two if statements
另一种方法(如果模板差异很大)是执行以下操作:
并在视图中设置 choice_template 。
Another way to do this (if the templates differ a lot) would be to do something along the lines of:
and set choice_template in the view.