2017-02-26 21 views
2

models.py:如何根據對象的字段賦值在Django模板HTML類

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') 

views.py通過context把這個對象傳遞到HTML模板。我想檢查(在HTML中)a_lot_of_text具有什麼樣的外觀,並且使用它的<div>元素使用certan class。換句話說,我想水木清華這樣的:

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

因爲在a_lot_of_text很多word我想檢查我的課1次,在我的for-block之前,並在那裏使用它。我想我可以製造my own assignment Tag - 這是正確的解決方案嗎?

回答

2

是的,你可以使用自定義標籤分配或者你可以做你想做的使用內置的標籤withhttps://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 %} 

而且,如果你正在尋找簡單的解決方案 - 讓名字或你的CSS-基於appearance值的類。 然後你只需要使用appearance的值,並添加'-class':

{% for word in object.value %} 
    <div class="{{ object.appearance }}-class">{{ word }}</div> 
{% endfor %} 
相關問題