models.py:
class MyText(models.Model)
value = models.TextField()
appearance = models.Charfield(
max_length=50,
choices=(
('bold', 'Bold'),
('italic', 'Italic'),
)
)
对象
a_lot_of_text = MyText(value='a lot of text', appearance='bold')
我通过context
中的views.py
将此对象传递到HTML模板。我想检查(在HTML中)a_lot_of_text
具有什么样的外观,并使用certan class
作为其<div>
元素。换句话说,我想得到这样的结论:
mytemplate.html(伪代码):
<style>
bold_class {...}
italic_class {...}
</style>
{% if object.appearance == 'bold' %}
{% somehow i will use 'bold_class' %}
{% elif object.appearance == 'italic' %}
{% somehow i will use 'italic_class' %}
{% endif %}
{% for word in object.value %}
<div class="{{class_that_i_have_chosen_in_if-block}}">{{word}}</div>
{% endfor %}
因为word
中有很多a_lot_of_text
我想在我的for-block
之前检查我的课程,并在那里使用它。我想我可以my own assignment Tag - 这是正确的解决方案吗?
答案 0 :(得分:2)
是的,您可以使用自定义分配标记,也可以使用内置代码with
https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#with
# models.py
class MyText(models.Model)
value = models.TextField()
appearance = models.Charfield(
max_length=50,
choices=(
('bold', 'Bold'),
('italic', 'Italic'),
)
)
def class_name(self):
if self.appearance == 'bold':
...
return 'bold-class'
elif self.appearance == 'italic':
...
return 'italic-class'
...
# template.html
{% with block_class=object.class_name %}
{% for word in object.value %}
<div class="{{ block_class }}">{{ word }}</div>
{% endfor %}
{% endwith %}
但是,如果您正在寻找简单的解决方案 - 根据appearance
值获取名称或您的CSS类。
然后你只需要使用appearance
值并在其中添加'-class':
{% for word in object.value %}
<div class="{{ object.appearance }}-class">{{ word }}</div>
{% endfor %}