【问题标题】:Python code works but not when translated into Jinja?Python 代码有效,但翻译成 Jinja 时无效?
【发布时间】:2020-01-14 14:54:30
【问题描述】:

当有元素和没有元素时,我试图渲染数组中的所有元素。当该位置没有元素时,我想显示该位置没有练习(元素)。这需要一小段代码,它在 python 中有效,但在 Jinja 中无效。除非我错过了两种语言之间的差异,否则这对我来说没有意义。

我首先在 python 中编写代码的原因是因为我已经尝试了一段时间来让它工作。我想如果我写了 python 我可以翻译它,但我猜不是?

工作 python 代码:

dailyExercise = [('Exercise 1', 1), ('Exercise 2', 3)]
for x in range(dailyExercise[-1][-1]):
    print(x+1)
    isExercise = False
    for exercise in dailyExercise:
        if exercise[-1] == x+1:
            print(exercise[0])
            isExercise = True
            break;
    if isExercise == False:
        print("no exercise")

无法使用 Jinja 代码:

{% for x in range(dailyExercise[-1][-1]) %}
    <p>Day {{x+1}}</p>
    {%set isExercise = False%}
    {% for exercise in dailyExercise%}
        {% if exercise[-1] == x+1 %}
            {%set isExercise = True%}
            <p>{{exercise[0]}}</p>
        {% endif %}
    {% endfor %}
    {% if isExercise == False%}
    <p>no exercise</p>
    {% endif %}
{% endfor %}

Python 会打印出来:

1                                                                      
Exercise 2                                                             
2                                                                      
no exercise                                                            
3                                                                      
Single leg balance abd/adduction 

Jinja 呈现这个:

Exercise 2
no exercise
Day 2
no exercise
Day 3
Single leg balance abd/adduction
no exercise

【问题讨论】:

    标签: python html flask jinja2


    【解决方案1】:

    一般来说,虽然在 Jinja 中可能创建复杂的分支逻辑,但它通常是错误的地方。除了 {% %} 的视觉混乱之外,模板尽可能用于客户端代码,而不是业务逻辑。

    我在这里的第一种方法是在 Python 中处理数组,创建一个新的数组,其中包含例如 None 用于缺少的练习。然后简单地遍历 Jinja 中的新数组 checking for None,并呈现适当的 HTML。如果需要访问当前项的索引,可以使用loop.index and loop.index0 变量。

    【讨论】:

    • Flask 中的view 是在传入请求被路由后响应的代码。它不使用与其他框架相同的术语。您也不会在模板中打印任何内容;值被渲染。
    • 谢谢。我在 MVC 中使用“视图”,但即使这样也不是完全正确的划分。我已经调整了措辞。
    猜你喜欢
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 2019-03-14
    • 2013-11-25
    • 2018-09-09
    • 1970-01-01
    相关资源
    最近更新 更多