2013-04-29 163 views
0

我是Django的新手,并且有一个基本问题。我创建了一个Django模板,并希望将外部变量传递给它,该变量控制colspan标记。我尝试了几次,但无法提供变量。我感谢任何帮助。将变量传递给Django模板

Python代码:

def getdjtemplate(th_span="1"): 
    dj_template =""" 
    <table class="out_"> 
    {# headings #} 
     <tr> 
     {% for heading in headings %} 
      <th colspan={{ %s }}>{{ heading }}</th> 
     {% endfor %} 
     </tr> 
    </table> 
    """%(th_span) 
    return dj_template 

我想我不应该用这个,但不知道如何解决它。

<th colspan={{ %s }}>{{ heading }}</th> 

回答

1

您刚刚返回一个字符串。您必须调用django方法来渲染模板:

from django.template import Context, Template 
def getdjtemplate(th_span="1"): 
    dj_template =""" 
    <table class="out_"> 
    {# headings #} 
     <tr> 
     {% for heading in headings %} 
      <th colspan={{ th_span }}>{{ heading }}</th> 
     {% endfor %} 
     </tr> 
    </table> 
    """ 
    t = Template(dj_template) 
    headings = ["Hello"] 
    c = Context({'headings':headings, 'th_span':th_span}) 
    return t.render(c) 
+0

谢谢。我忘记了将'th_span':th_span'包含到'Context'调用中 – 2013-04-29 22:11:10

相关问题