簡體   English   中英

django templatetags template,將{{}}方法調用與模板標記上下文變量組合

[英]django templatetags template , combine {{ }} method call with template tag context variable

我試圖使一個模板標簽的結果依賴於另一個模板標簽。 用例如下。 我有一個標題列表,其中包含我想在表中顯示的所有列+它們正在顯示的模型的列+是否可見。

LIST_HEADERS = (
    ('Title', 'title', True),
    ('First Name', 'first_name', True),
    ('Last Name', 'last_name', True),
    ('Modified At', 'modified', False),
)

現在我有一個templatetag,可以打印出所有標題。 因此,我想創建一個模板標簽,將表的主體打印出來。 因此,我想獲取標題列表並檢查哪個標題可見,並希望相應地顯示或隱藏我的值。

因此,我在下面創建了templatetag模板:

<tr class="{% cycle odd,even %}">
  {% for header in headers %}
  {% if header.visible %}
    <td><a href="{{ model_instance.get_absolute_url|escape }}">{{ model_instance.title }}</a></td>
  {% else %}
    <td style="visibility:hidden;"><a href="{{ model_instance.get_absolute_url|escape }}">{{ model_instance.title }}</a></td>
  {% endif %}
  {% endfor %}
</tr>

您會在此處看到值{{model_instance.title}}。 這個值我想在運行時更改為model_instance.title,model_instance.first_name,model_instance.last_name,...。

因此,我正在尋找一種方法將{{model_instance}}與header.model_column結合起來。

model_column等於LIST_HEADERS中的第二個條目。 因此,model_column將是title,first_name等。

因此解決方案將類似於[pseudocode] {{model_instance.header.model_column}} [pseudocode]

..因此我搜索了一種如何將django模板方法調用與django模板標簽屬性相結合的方法..呵呵..聽起來很瘋狂:D

我希望我解釋得足夠好! 也許有一個更容易解決我的問題的方法。 但這對我來說似乎很通用且容易實現。

我將其用作過濾器,因為它們提供了一種簡單的方法來根據變量的值呈現結果。

@register.filter
def field_from_name(instance, field_name):
    return getattr(instance, field_name, None)

然后在模板中:

{{ model_instance|field_from_name:header.model_column }} 

簡化一下。

首先,了解Django模板語言實際上可以做的事情。 不多 它可以引用變量,列表和字典。

如果您在視圖函數中執行所有“工作”,則更為簡單。

show = [ ]
for  title, field_name, visible in LIST_HEADERS:
     if visible: style= "visibility:hidden"
     else: style= ""
     show.append( (style, title, getattr(object,field_name) )
render_to_response( "template", { 'show_list': show, ... }, ... )

在您的模板中

{% for style, name, value in show_list %}
<tr class="{% cycle odd,even %}">
    <td class="{{style}}"><a href="...">{{value}}</a></td>
{% endfor %}

確實,我建議您從視圖函數中刪除LIST_HEADERS。

show = [ 
    ("", 'Title', object.title),
    ("",'First Name', object.first_name),
    ("",'Last Name', object.last_name),
    ("visibility:hidden",'Modified At', object.modified),
]
render_to_response( "template", { 'show_list': show, ... }, ... )

我發現上述內容更容易使用,因為它是顯式的,並且在視圖函數中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM