Python 将变量传递给Django模板
我是Django的新手,有一个基本问题。我创建了一个Django模板,并希望将外部变量传递给它,它控制Python 将变量传递给Django模板,python,django,Python,Django,我是Django的新手,有一个基本问题。我创建了一个Django模板,并希望将外部变量传递给它,它控制colspan标记。我尝试了好几次,但无法传递变量。谢谢你的帮助 Python代码: def getdjtemplate(th_span="1"): dj_template =""" <table class="out_"> {# headings #} <tr> {% for heading in headings
colspan
标记。我尝试了好几次,但无法传递变量。谢谢你的帮助
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
定义getdjtemplate(th_span=“1”):
dj_模板=”“
{#标题}
{标题%中的标题为%}
{{heading}}
{%endfor%}
“%”(第span页)
返回dj_模板
我想我不应该使用这个,但不知道如何修复它
<th colspan={{ %s }}>{{ heading }}</th>
{{heading}
您只是返回一个字符串。必须调用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)
来自django.template导入上下文,模板
def getdjtemplate(th_span=“1”):
dj_模板=”“
{#标题}
{标题%中的标题为%}
{{heading}}
{%endfor%}
"""
t=模板(dj_模板)
标题=[“你好”]
c=上下文({'headers':headers'th_span':th_span})
返回t.render(c)
谢谢。我忘记将'th\u span':th\u span
包含到“Context”调用中