Django中的页面范围变量



我是Django和Python的新手。在我熟悉的其他框架中,我试图实现的是如此简单。但我在Django的互联网上找不到一个简单/快速的方法。如果不必要的话,我不会将模板用于这个非常基本的操作。

{% for tweet in tweets.itertuples %}
{% if tweet.sent == 'pos' %}
{% with color_class='text-success' %}
{% endwith %}
{% with fa_class='smile' %}
{% endwith %}
{% elif tweet.sent == 'neg' %}
{% with color_class='text-danger' %}
{% endwith %}
{% with fa_class='frown' %}
{% endwith %}
{% else %}
{% with color_class='text-muted' %}
{% endwith %}
{% with fa_class='meh' %}
{% endwith %}
{% endif %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<small class="text-muted">{{ tweet.unix }}</small>
</div>
<h2>
<i class="fa fa-{% if true %} smile {% endif %} text-{% if true %} success {% endif %}"></i>
<a class="article-title text-{% if tweet.sent == 'pos' %} 'success' {% endif %}" href="#">
{{ tweet.sentiment }}
</a>     
</h2>
<p class="article-content">{{ tweet.tweet }}</p>
</div>
</article>
{% endfor %}

下面的部分没有按照我的意愿进行渲染。

<i class="fa fa-{% if true %} smile {% endif %} text-{% if true %} success {% endif %}"></i>
<a class="article-title text-{% if tweet.sent == 'pos' %} 'success' {% endif %}" href="#">

它呈现的内容:

<i class="fa fa- text-"></i>
<a class="article-title text-" href="#">-0.6</a>

我想要什么:

<i class="fa fa-smile text-success"></i>
<a class="article-title text-success" href="#">

在这一点上,我可能需要的是设置页面范围变量。但是怎么做呢?

在views.py:中

tweets['sent_icon_class'] = tweets['sentiment'].apply(lambda x: ("smile" if x > 0 else "frown" if x < 0 else "meh"))
tweets['sent_color_class'] = tweets['sentiment'].apply(lambda x: ("success" if x > 0 else "danger" if x < 0 else "muted"))

在index.html中:

{% for tweet in tweets.itertuples %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<small class="text-muted">{{ tweet.created_at }}</small>
</div>
<h2>
<i class="fa fa-{{ tweet.sent_icon_class }} text-{{ tweet.sent_color_class }}"></i>
<a class="article-title text-{{ tweet.sent_color_class }}" href="#">
{{ tweet.sentiment }}
</a>
</h2>
<p class="article-content">{{ tweet.tweet|safe }}</p>
</div>
</article>
{% endfor %}

最新更新