xenogenesi::blog
memento
3d adt android apache2 app apt aria2 build bullet cflags chromium codeigniter debian demoscene dependencies dpkg driver emulator freeglut gcc gfx git glut htaccess javascript json kernel linux make metalink minimal mysql opengl php python raspbian realtime rpi specs template toolchain update-alternatives video wifi wordpress

python/jinja2 for metaprogramming

A simple example using python and jinja2 template engine, I’m evaluating it for doing some metaprogramming (generating php/html and javascript from a json).
I evaluated also fmpp/freemarker but jinja2 is just so simple and its syntax doesn’t conflict with php/html/javascript/css.

test.py:

from jinja2 import Template
import json

rootJson = json.load(open('test.json', 'r'))

tpl = Template(open('test.jinja', 'r').read().decode('utf-8'))
print tpl.render(root=rootJson).encode('utf-8')

test.json:

{
    "test": "valueèè&&"
}

test.jinja:

Hello {{ root.test|e }}

Php and Javascript template engines

I thought would be nice to have a template engine with the same syntax for both Php and Javascript, I’m thinking about a website which could work on Php only then scale with Javascript, below a list of something that already exist:

  1. jquery-tmpl: jquery-tmp is deprecated from jquery and abandoned.
  2. Smarty: smarty have a nice syntax and is powerful but too much for my needs, I didn’t checked the status and compatibility of jsmart.
  3. mustache: so far the most interesting, pre-compiled templates in Javascript, cached on Php, same syntax for both languages, there’s also handlebars.js which is compatible to some degree.
  4. twig: interesting but the compatibility of twig.js is still partial, a subset.
  5. underscore: would have been interesting because is a dependency of Backbone.js, sadly the syntax is different, would require a different template for each language.

So, mustache seems to be most interesting, I’ll give a try sooner or later, in the while I been tempted (still) to write my own, inspired by something simple like JavaScript template engine in just 20 lines and JavaScript Micro-Templating. The target would be a template engine with the same exact syntax for both Php and Javascript, a generator, script or command, which given a template would create a function for both the languages (eventually any language introducing a output backend concept).

Doing some fast test immediately shown an horrific implementation design, Javascript’s (json) objects are unsorted (arrays are sorted).