如何根据对象的字段值在 django 模板中分配 HTML 类

cMe*_*IHo 5 django django-templates

模型.py:

class MyText(models.Model)
    value = models.TextField()
    appearance = models.Charfield(
        max_length=50, 
        choices=(
            ('bold', 'Bold'),
            ('italic', 'Italic'),
        )
    )
Run Code Online (Sandbox Code Playgroud)

目的:

a_lot_of_text = MyText(value='a lot of text', appearance='bold')
Run Code Online (Sandbox Code Playgroud)

我将这个对象通过contextin传递views.py到 HTML 模板中。我想检查(在 HTML 中)有什么样的外观a_lot_of_text,并使用 certanclass作为其<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 %}
Run Code Online (Sandbox Code Playgroud)

因为有很多worda_lot_of_text我想检查我的班级 1 次,在我之前for-block并在那里使用它。我想我可以制作自己的作业标签- 这是正确的解决方案吗?

小智 5

是的,您可以使用自定义分配标签,也可以使用内置标签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 %}
Run Code Online (Sandbox Code Playgroud)

而且,如果您正在寻找简单的解决方案 - 根据appearance值获取名称或您的 CSS 类。然后你只需要使用appearancevalue 并添加 '-class' 到它:

{% for word in object.value %}
    <div class="{{ object.appearance }}-class">{{ word }}</div>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)