简体   繁体   中英

Passing variables to a Django template

I am new to Django and have a basic question. I created a Django template, and would like to pass external variables to it, which controls colspan tag. I tried several times, but could not deliver the variable. I appreciate any help.

Python Code:

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

I think I should not use this, but not sure how to fix it.

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

You are just returning a string. You must call the django methods to render the template:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM