TAGS :Viewed: 16 - Published at: a few seconds ago

[ Processing ember.js tagged html with python ]

I have the following scenario:

  1. We are using web2py in the server side
  2. We are serving some ember.js pages
  3. Currently those ember.js pages are inside an iframe, because ember.js and web2py conflict with template {{ }} marks. That means we can not easily mix web2py templates and ember.js templates.
  4. So I have implemented the helper class solution: class em(DIV)
  5. Now I want to process the original ember-tagged html files, and produce the em-tagged files, integrating ember.js and web2py templating-systems into a cohesive unit.

For that I need to change all instances of {{XXX}} in the ember.js files to {{=em('XXX')}}, including instances which span over several lines. I am thinking of going regex here, but I would like to avoid reinventing the wheel (and having to handle strange corner-cases)

Can you think of a generic method in python of parsing these kind of templates. It is simply a matter of looking for start and end delimiter ({{ and }}), and putting an =em('XXX'), handling newlines, and keeping the format (that is, keep the newlines if there are some).

Note: this is actually not ember.js specific; it could apply to any multi-line delimiter-based templating system.

Answer 1


Note, in the trunk version of web2py (which will be released as web2py 2.0 in the next few days), you can now specify custom delimiters for the templates -- so you can change the web2py delimiters so they no longer conflict with the ember.js delimiters. For example, in a model file:

response.delimiters = ['{%', '%}']

Then in your web2py templates, you can do:

{%=P('hello world')%}
<p>{{ember template code}}</p>
{%=P('{{ember template code generated by web2py}}')%}

which will produce:

<p>hello world</p>
<p>{{ember template code}}</p>
<p>{{ember template code generated by web2py}}</p>

Note, response.delimiters is set on each request, so if you don't want to change the web2py delimiters on all pages but only those that include ember code, you can set response.delimiters conditionally (either by setting it in the specific actions that need it, or by checking the requested controller and/or function in a model file). For example, in a model file:

if request.function in ['action1', 'action2', 'action3']:
    response.delimiters = ['{%', '%}']

or in a controller:

def action1():
    response.delimiters = ['{%', '%}']
    [etc.]

Answer 2


It may worth trying an approach with keeping all your Ember.js stuff in separate files and do not mix it with with web2py templates. Fortunately, Ember.js easily allows to do it.