Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign HTML class in django template depending object's field value

models.py:

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

object:

a_lot_of_text = MyText(value='a lot of text', appearance='bold')

I pass this object via context in views.py into HTML template. And I want to check (in HTML) what kind of appearance a_lot_of_text has, and use certan class for its <div> element. In other words, I want to get smth like this:

mytemplate.html (pseudocode):

<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 %}

Because there is a lot of word in a_lot_of_text I would like to check my class 1 time, before my for-block and use it there. I think I could make my own assignment Tag - is it correct solution?

like image 450
cMeIIIHo Avatar asked Feb 26 '17 22:02

cMeIIIHo


1 Answers

Yes, you can use custom assignment tag or you can do what you want using built-in tag 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 %}

But also, if you are looking for simple solution - get names or yours CSS-classes based on appearance value. Then you just need to use appearance value and add '-class' to it:

{% for word in object.value %}
    <div class="{{ object.appearance }}-class">{{ word }}</div>
{% endfor %}
like image 83
Anton Perepelitcyn Avatar answered Oct 14 '22 11:10

Anton Perepelitcyn