Reputation: 7550
UPDATE 1 ADDED UPDATED CODE
I have a django template on app engine. Currently all my data is in several templates and I would like to read the templates off disk. Very easy, but I would like to get the values out of these templates in AppEngine.
eg. file : 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%}
Can I load and read these template into some value and go.
template['price']
which would be
$259
I can easily inject data into the template, but I want to parse out the data between my block tags.
UPDATED 2 With the help of aaronasterling (THANKS) the final code is this. Final code to get the value out of a Django template on app engine. path = os.path.join(os.path.dirname(file), 'home/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())
Upvotes: 0
Views: 445
Reputation: 71014
Update 1 fixed to traverse the whole node tree.
Update 2 Actually tested it so now it works.
Here's one way to do it.
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
Upvotes: 1
Reputation: 156158
Sounds like you've shot yourself in the foot. Lets just pretend we aren't to blame and fix it:
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']
Upvotes: 3