Use Python on mustache template files - Printable Version

+- (https://diviera.com)
+-- Forum: Coding (https://diviera.com/forumdisplay.php?fid=1)
+--- Forum: Python (https://diviera.com/forumdisplay.php?fid=2)
+--- Thread: Use Python on mustache template files (/showthread.php?tid=6)



Use Python on mustache template files - Janusz - 12-17-2020

To use mustache templating language with Python we need chevron.

pip install chevron

If you get some red errors try this:
pip install --user chevron

If you still get red errors, sorry I'm a NOOB.

Next, add chevron.exe to PATH, like pip message suggest.

Example template file (diviera.txt):
<title>{{title}}</title>
This is {{name}}!

Python code:
import chevron

strings = {'title': 'Fantastic title',
            'name':'Sparta'}

with open('diviera.txt', 'r') as f:
    fillup = chevron.render(f, strings)    

with open('diviera_final.txt', 'w') as nf:
    nf.write(fillup)



RE: Use Python on mustache template files - Janusz - 12-17-2020

Nested template fantastic solution.
First render stuff that you need insde master template, add it to dictionary and render master template.

Master template (diviera_master.txt):

<title>{{title}}</title>
{{content}}
Use {{{content}}} (triple mustache) if you want use HTML as a content.

Content template (diviera_content.txt):
This is {{name}}!

Python code:
import chevron

strings = {'title': 'Fantastic title',
            'name':'Sparta'}

#content
with open('diviera_content.txt', 'r') as cf:
    newContent = chevron.render(cf, strings)
    contentString = {'content' : newContent}
    strings.update(contentString)

#master
with open('diviera_master.txt', 'r') as f:
    fillup = chevron.render(f, strings)
    print(fillup)


#result
with open('diviera_final.txt', 'w') as nf:
    nf.write(fillup)