【问题标题】:Django Tutorial Part 3 - Code ClarificationDjango 教程第 3 部分 - 代码说明
【发布时间】:2017-08-21 16:00:20
【问题描述】:

这里是 Django 新手。我正在做 Django 教程,虽然我可以盲目地遵循代码,但我只是对它的工作原理感到困惑。我知道 {% code %} 是允许我们将 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 %}

【问题讨论】:

    标签: html python-3.x django-templates


    【解决方案1】:

    {{ variable }} syntax in Django templates 用作变量的占位符

    如果你想在控制台检查它是如何工作的,启动 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!
    

    【讨论】:

      猜你喜欢
      • 2018-11-13
      • 1970-01-01
      • 2016-12-24
      • 2018-11-02
      • 2014-04-06
      • 1970-01-01
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      相关资源
      最近更新 更多