Django 教程第 3 部分 - 代码说明



Django 新手在这里。我正在做 Django 教程,虽然我可以盲目地遵循代码,但我只是对它是如何工作的感到困惑。我知道 {% 代码 %} 允许我们将 python 代码插入到 html 中,我没有得到的是以下行:

<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}

我只想解释一下带有变量的两个大括号如何转换为该变量的字符串表示形式。

我问是因为我尝试自己在解释器中做类似的操作,但没有得到相同的结果。

{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}
</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

Django 模板中的{{ variable }}语法用作变量的占位符

如果你想检查它在控制台上是如何工作的,请启动 django shell:

$ django-admin shell
>>> from django.template import engines
>>>
>>> django_engine = engines['django']
>>> template = django_engine.from_string("Hello {{ name }}!")
>>> context = {'name': 'John'}
>>> template.render(context)
Hello John!

最新更新