Create a mechanism to replace template entries with json objects in python

I want to create a python engine that can replace tags in a template file with objects from json? I made money on python-based engines that use regex, but they are too complicated, and I'm a little confused about how to start a crawl. Any started code will help

Json file example

{
  "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 identified between <%% EACH .. %%> AND <%% END %%> and basically output html

+4
source share
2 answers

Alex Mitchells ( python), GIT

,

  • Parse template file - build . node,

  • , , ,

  • json , , AST html

  • .

, Alex mitchells , ( ) reg exp , HTML-.

+3

, <%% %%>. , .

>>> import re
>>> t='<h1><%% Songs.name %%></h1>'
>>> re.search(r'<%%(.+?)%%>', t).groups()
(' Songs.name ',)

, , , shlex . , , , .

, , json. python dicts, html.

, , jinja chameleon , , .

+2

All Articles