2011-04-04 45 views
1

Hey Stack先生溢出! 我想在不同的信息显示在同一个块取决于一个变量“选择”,这是一个简单的int。我打算这样做的方式将是有点像娄代码:现在使用django模板中的同一个块根据变量显示不同的信息

{% 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}}&deg </p> 
{%endblock one%} 

{%if choice1 == 2 %} 
    {%block two%}  
     <p>The temperature in {{city}} is {{temperature}}&deg </p> 
    {%endblock two%} 
{% endif %} 

{%comment%} 
    {%if choice1 == 2 %} 
     {%block two%} 
      <p>The temperature in {{city}} is {{temperature}}&deg </p> 
     {%endblock%} 
    {% endif %} 
{%endcomment%} 

{%block two%} 
    <form method="post"> 
    {%csrf_token%} 
    {% if new_event %} 
     <b><p>{{new_event}}</p></b> 
    {% endif %} 
{%endblock%} 

,我遇到的问题是,模板不喜欢,有同名的两个街区模板。由于某种原因,它似乎并不关心{% if %}声明,该声明检查{% block %}应该去的地方。我认为{% if %}声明只会根据其参数执行其内部的内容,但似乎没有这样做。它显示在{% if %}里面的所有东西,无论什么“choice1”都是一样的:(有没有人有任何想法,我可能会解决这个问题?谢谢

回答

3

把逻辑里面的块,而不是有两个相同的块名

相反的:

{%if choice1 == 2 %} 
    {%block two%}  
     <p>The temperature in {{city}} is {{temperature}}&deg </p> 
    {%endblock two%} 
{% endif %} 

{%comment%} 
    {%if choice1 == 2 %} 
     {%block two%} 
      <p>The temperature in {{city}} is {{temperature}}&deg </p> 
     {%endblock%} 
    {% endif %} 
{%endcomment%} 

{%block two%} 
    <form method="post"> 
    {%csrf_token%} 
    {% if new_event %} 
     <b><p>{{new_event}}</p></b> 
    {% endif %} 
{%endblock%} 

使用:

{% block two %} 
    {% if choice1 == 2 %} 
     <p>The temperature in {{city}} is {{temperature}}&deg </p> 
    {% else %} 
     <form method="post"> 
     {%csrf_token%} 
     {% if new_event %} 
      <b><p>{{new_event}}</p></b> 
     {% endif %} 
    {% endif %} 
{% endblock %} 
1

把if放在块内。一个街区,两个if语句

{% block two %} 
    {% if choice == 1 %} 
     <p>Some Content</p> 
    {% endif %} 
    {% if choice == 2 %} 
     <p>Other Content</p> 
    {% endif % 
{% endblock two %} 
0

另一种方式来做到这一点(如果模板差别很大)是做线沿线的东西:在视图

{% extends choice_template %} 

,并设置choice_template。

相关问题