As of 0.9.5 release, Pylons supports Myghty as a default templating language. This recipe provides instructions on how to use Mako instead of/alongside with Mighty. Text is extracted from the pylons wiki, original author is James Gardner.
| Useful Information Note: Mako is the default from 0.9.6rc1 onwards. Much of the below info is inaccurate for 0.9.6rc1 onwards. |
Making Mako the default
First get hold of the latest copy of Mako:
1 | easy_install -U Mako |
Then change this line in yourproject/config/middleware.py:
1 | config.init_app(global_conf, app_conf, package='yourproject') |
to this:
1 | config.init_app(global_conf, app_conf, package='yourproject', template_engine='mako') |
Then you can use the standard render() and render_response() functions as normal and they will use Mako templates instead of Myghty ones.
If your templates are UTF-8 encoded you should set these template options in your environment.py:
1 2 3 4 | tmpl_options = {} tmpl_options['mako.input_encoding'] = 'UTF-8' tmpl_options['mako.output_encoding'] = 'UTF-8' tmpl_options['mako.default_filters'] = ['decode.utf8'] |
Running Mako and Myghty Together
If you wish to stick with Myghty as your main template engine but use Mako as well you should easy_install Mako as before but add the following to your config/middleware.py file after config.init_app():
1 2 | mako_opts = {} config.add_template_engine('mako', 'yourproject.templates', mako_opts) |
You can specify any Mako options to the TemplateLookup() class by adding them to mako_opts. For example the following would set the direcetory for storing cached templates to be /tmp/mako_modules:
1 | mako_opts = {'mako.module_directory':'/tmp/mako_modules'} |
Now that Mako is setup you can use it in your controllers. For example, add a TemplateTest controller:
1 | paster controller TemplateTest |
then edit it to look like this:
1 2 3 4 5 6 | from yourproject.lib.base import * class TemplatetestController(BaseController): def myghty(self): return render_response('test.myt', world="World") def mako(self): return render_response('mako', 'test.html', world="World") |
You will also need to add the two templates, templates/test.myt using Myghty should look like this:
1 | Hello <% ARGS['world'] %> Myghty! |
and templates/test.html using Mako should look like this:
1 | Hello ${world} Mako! |
You can then view the output by serving the project:
1 | paster serve --reload development.ini |
and visiting http://localhost:5000/TemplateTest/myghty and http://localhost:5000/TemplateTest/mako