代码之家  ›  专栏  ›  技术社区  ›  John Ballinger

Appengine Django模板-读取模板标记

  •  0
  • John Ballinger  · 技术社区  · 14 年前

    更新1 添加了更新的代码

    我在app engine上有一个django模板。目前我的所有数据都在几个模板中,我想从磁盘上读取这些模板。很简单,但是我想在AppEngine中从这些模板中获取值。

    文件:p1.html

    {%block price%}$259{%endblock%}  
    {%block buy%}http://www.highbeam.co.nz/store/index.php?route=product/product&path=6&product_id=116{%endblock%}  
    {%block info%}http://www.inov-8.co.nz/oroc280.html{%endblock%}    
    

    我能把这些模板加载到某个值中并读取吗。

    template['price']
    

    那就是

    259美元

    我可以很容易地将数据注入模板,但是我想解析块标记之间的数据。

    更新2 在aaronasterling(谢谢)的帮助下,最终的代码是这样的。 从app engine上的Django模板中获取值的最终代码。 path=os.path.join(os.path.dirname( 文件 ),'主页/p2.html')

        file = open(path)
        entry = file.read()
        file.close()   
        entry = entry.replace("{% extends \"product.html\" %}","")   
    
        t = Template(entry) 
    
        product = {}
        for node in t.nodelist[0].nodelist  :   
           if hasattr(node, 'name'):
              product[node.name] = node.render(Context()) 
    
    2 回复  |  直到 14 年前
        1
  •  3
  •   SingleNegationElimination    14 年前

    听起来像是你的脚中弹了。让我们假装不该责怪我们并解决它:

    entry = """{%block price%}$259{%endblock%}  
    {%block buy%}http://www.highbeam.co.nz/store/index.php?route=product/product&path=6&product_id=116{%endblock%}  
    {%block info%}http://www.inov-8.co.nz/oroc280.html{%endblock%}   """
    
    parsedentry = dict([(j[0].split(' ')[-1], j[-1]) for j in [i.partition("%}") for i in entry.split("{%endblock%}")] if j[0].split(' ')[-1]])
    
    print parsedentry['price']
    
        2
  •  1
  •   aaronasterling    14 年前

    更新1 固定为遍历整个节点树。

    更新2 实际上已经测试过了,现在可以用了。

    这里有一种方法。

    from django.template import Template, Context
    
    t = Template(template_string) # get it with open(filename).read() I guess
    
    
    def get_block_contents(t, block_name, context=None):
        if context is None:
            context = Context()
        stack = t.nodelist[:]
        while stack:
            node = stack.pop()
            if hasattr(node, 'name') and node.name == block_name:
                return node.render(context)
            if hasattr(node, 'nodelist'):
                stack.extend(node.nodelist)
        return False # Or raise an error