【问题标题】:How do I solve this TemplateSyntaxError in Django that says "Could not parse the remainder"如何解决 Django 中显示“无法解析剩余部分”的 TemplateSyntaxError
【发布时间】:2019-12-20 10:31:22
【问题描述】:

我正在尝试使用 for 循环重复呈现一段 HTML 代码。但是当我重新加载浏览器时,Django 会抛出 TemplateSyntaxError

<div class="carousel-item active">
    {% for number in range(3) %}
    <!--Slide {{ number + 1 }}-->
    <div class="row">
        {% for number in range(6) %}
        <!--Slide 1 Col {{ number + 1 }}-->
        <div class="col-lg-2">
            <div class="card" style="width: 100%;">
                <img class="card-img-top" src="..." alt="Card image cap">
                <div class="card-body">
                    <h5 class="card-title">Card title</h5>
                    <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
                    <a href="#" class="btn btn-primary">Go somewhere</a>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>
    {% endfor %}
</div>

我希望在 for 循环内重复渲染块,但在 / 处得到“TemplateSyntaxError” 无法解析余数:来自“range(3)”的“(3)”

【问题讨论】:

  • 您不能进行函数调用(在模板中使用参数),所以range(3) 将不起作用。将其通过上下文传递给模板,或使用 Jina。

标签: python django


【解决方案1】:

Django 不允许在模板中进行函数调用(带参数)以及下标。理由是业务逻辑不应该是模板的一部分。因此,您可以通过上下文将range(3) 和range(6) 对象传递给模板。 {{ number + 1 }} 也不起作用,因为也不支持此类运算符。

另一种方法是使用Jinja,这是一个模板引擎,确实允许在模板中使用这种 Python 语法。

由于数字很小,第三种选择是使用字符串文字代替:

<div class="carousel-item active">
    {% for row in '123' %}
    <!--Slide {{ row }}-->
    <div class="row">
        {% for col in '123456' %}
        <!--Slide 1 Col {{ col }}-->
        <div class="col-lg-2">
            <div class="card" style="width: 100%;">
                <img class="card-img-top" src="..." alt="Card image cap">
                <div class="card-body">
                    <h5 class="card-title">Card title</h5>
                    <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
                    <a href="#" class="btn btn-primary">Go somewhere</a>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>
    {% endfor %}
</div>

【讨论】:

    猜你喜欢
    • 2011-07-11
    • 2015-03-06
    • 2011-11-06
    • 2018-03-31
    • 2016-06-04
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    • 2013-10-04
    相关资源
    最近更新 更多