Create a engine to replace template entries with json objects in python
json, python, template-engine
Solution
Check out Alex Mitchells blog on templating (python based), it's extremely helpful, and the related GIT here
Basically,
Take input files on command line
Parse template file - build Abstract Syntax tree to parse easily. Create a node base type, and then for each new type implement a concrete class
Build stack to keep track of loops, pop when loops close, look for errors of missing loop ends
Parse json file, build dictionary of objects, map AST entries and replace in html
Write output to file.
I have a version of this based on Alex mitchells engine here, where I've fixed some issues with the original one( and put it in some code of my own) and will be trying to get rid of the reg exp based matching and put in contextual matching, because regular expressions dont work too well on large complex HTML data.
Problem
I want to create an engine in python that can replace tags in a template file with objects from json? I've loooked at python based engines that use regex but they are overly complicated and I am a little confused as to how to start an go about it. Any code to start would help Sample json file ``` { "webbpage": { "title": "Stackoverflow" }, "Songs": { "name": "Mr Crowley" }, "CoverArtists": [ { "name": "Ozzy", "nicknames": ["Ozzman","Ozzster"] }, { "name": "Slipknot", "nicknames": ["Slip"] } ] } ``` Sample template file ``` <html> <head> <title><%% webbpage.title %%></title> </head> <body> <h1><%% Songs.name %%></h1> <%% EACH CoverArtists artist %%> <%% artist.name %%> <%% EACH CoverArtists.nicknames nickname %%> <p><%% nickname %%></p> <%% END %%> <%% END %%> </body> </html> ``` Basically variables are identified between <%% and %%> and loops are identifed between <%% EACH .. %%> AND <%% END %%> and basically output html