Template engine for source code generation: Jinja2 vs. Mako

At line of development process automation, I designed and built special script and methodology for easy and fast generation of hard coded data definition in the source code by provided relative data composed separately in the spreadsheets. The script loads csv data and render it into special section in existing source code file by the template provided in the same file.
The script is implemented in python, so, I need some cool template engine. I was looking at Mako and Jinja2.
After brief research I was try Mako. But it was very ugly at line of source code generation. Just look at this example:

# coma separator example

print Template("""<% c = 0 %>% for i in list:<%    coma = ''    if c < len(list) - 1: coma = ','    c += 1%>${i}${coma}% endfor""").render(list=(0,1,2))

So, I decided to use Jinja2. It’s much better for source code generation and looks like more power template engine as a whole. Here is several cool features I’m able to implement with jinja2:

  • separator
  • multiline indentation
  • correct new lines


{% set gunTypes = tables.gunTypes -%}{%- for g in gunTypes -%}{%- if g.shoot_width -%}{%- if loop.index0 > 0 %},{% endif -%}new GunType(                   {{g.id}},                   new Shape({{g.base_width}}, {{g.base_height}}, new <int>[                           {{g.base_shape|replace('n', 'n                               ')}}                   ]),                   new Shape({{g.shoot_width}}, {{g.shoot_height}}, new <int>[                           {{g.shoot_shape|replace('n', 'n                               ')}}                   ])           ){%- endif %}{%- endfor %}


new GunType(                   0,                   new Shape(1, 2, new <int>[                           1,1                   ]),                   new Shape(1, 1, new <int>[                           5                   ])           ),new GunType(                   1,                   new Shape(2, 1, new <int>[                           1,1                   ]),                   new Shape(2, 2, new <int>[                           0,5,                           5,0                   ])           )



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: