2011-04-10 128 views
2

免責聲明:這是關於my previous question的問題。如何在django的模板標籤中獲取模板的渲染輸出?

我試圖在Django中編寫一個模板標籤,它將呈現自己在Mako模板的主體內。我不確定這是否可以實現,但這對我的項目非常有用,可能還有很多其他人在Django中使用Mako模板。

這裏是我的標籤定義:

def extends_mako(parser, token): 
    # wishlist below, this code does not work but it's what I want to achieve 
    template_html = '' 
    while (node = parser.nodelist.pop()): 
     template_html += node.render() 

是解析器對象能夠呈現整個樹到這一點的?我現在唯一的想法是使用解析器對象來渲染(並從樹中移除)此節點之前的每個節點。然後,我會將輸出傳遞給Mako以呈現爲HTML,並將其用作我正在定義的節點的渲染函數的輸出。我的希望是,當模板上調用渲染時,它只需要渲染這個節點,因爲我的模板標籤已經完成了其他所有的編譯。目的是將extend_mako標記作爲樹中的最終標記。

我已經做了一些快速的pdb.set_trace調查,但我看不到任何有助於到目前爲止。

所以;是否有可能使用解析器對象,傳遞給模板標籤,編譯模板,並檢索最終的渲染輸出?

+0

刪除了包含Mako標記的編輯。這個問題的答案不涉及Mako。它明確地使用django模板標記來呈現django模板的當前總輸出。 – 2011-04-11 00:13:04

回答

1

這不是針對您的問題的解決方案,但可能會讓您朝正確的方向發展。我最近採用了Django的「無空間」模板標籤,並增加了支持,以便在調試時不會將空白字體去掉。

該模板標籤的

部分經過{%spaceless%}之間收集模板節點{%endspaceless%}標籤,這在理論上,可能讓你的節點前述的節點列表...

from django.conf import settings 
from django import template 
from django.utils.html import strip_spaces_between_tags 

register = template.Library() 

class SmartSpacelessNode(template.Node): 
    def __init__(self, nodelist): 
     self.nodelist = nodelist 

    def render(self, context): 
     content = self.nodelist.render(context) 
     #from here, you can probably delete the nodes after you've rendered 
     #the content to a variable, then render your tag 
     return content if settings.DEBUG else strip_spaces_between_tags(content.strip()) 

@register.tag 
def smart_spaceless(parser, token): 
    nodelist = parser.parse(('end_smart_spaceless',)) 
    parser.delete_first_token() 
    return SmartSpacelessNode(nodelist) 

希望能幫助你。

+0

這絕對是朝正確方向邁出的一步。然而,在django中渲染一個模板是'自下而上'的。我想從最底層獲取自上而下的節點。雖然節點列表很棒,但我根本不知道如何獲取它。 – 2011-04-13 03:49:25

+1

嗯。這是一個有趣的問題。我會做一些調查,看看我能想出什麼。 – Brandon 2011-04-13 04:07:00

+0

好吧。我無法使用Django的模板引擎提出解決方案。我之前沒有使用Jinja,但我確實注意到他們有一個「提前」編譯功能,可以幫助你:http://jinja.pocoo.org/ – Brandon 2011-04-15 14:50:56