Skip to content

Commit

Permalink
Merge pull request #2456 from getnikola/escape-to-template
Browse files Browse the repository at this point in the history
Fix #1227
  • Loading branch information
ralsina committed Aug 19, 2016
2 parents 322170c + 827d6f3 commit acd6db1
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGES.txt
Expand Up @@ -4,6 +4,7 @@ New in master
Features
--------

* Shortcode to escape to the template language (Issue #1227)
* Added link to raw file in listings (Issue #1995)
* New NO_DOCUTILS_TITLE_TRANSFORM (Issue #2382)
* Update options of chart directive to Pygal 2.2.3
Expand Down
13 changes: 13 additions & 0 deletions docs/manual.txt
Expand Up @@ -928,6 +928,19 @@ Then the output file will contain::

This uses the bar variable: bla

Finally, you can use a template shortcode without a file, by inserting the template in the shortcode itself::

{{% raw %}}
{{% template %}}
% for foo in bar:
<li> ${foo}
% endfor
{{% /template %}}
{{% /raw %}}

In that case, the template engine used will be your theme's and the arguments you pass, as well as the global
context from your ``conf.py``, are available to the template you are creating.

Redirections
------------

Expand Down
23 changes: 22 additions & 1 deletion nikola/nikola.py
Expand Up @@ -1452,7 +1452,14 @@ def render_shortcode(*args, **kw):
return render_shortcode

def _register_templated_shortcodes(self):
"""Register shortcodes provided by templates in shortcodes/ folders."""
"""Register shortcodes based on templates.
This will register a shortcode for any template found in shortcode/
and a generic "template" shortcode which will consider the content
in the shortcode as a template in itself.
"""
self.register_shortcode('template', self._template_shortcode_handler)

builtin_sc_dir = resource_filename(
'nikola',
os.path.join('data', 'shortcodes', utils.get_template_engine(self.THEMES)))
Expand All @@ -1470,6 +1477,20 @@ def _register_templated_shortcodes(self):
self.register_shortcode(name, self._make_renderfunc(
fd.read(), os.path.join(sc_dir, fname)))

def _template_shortcode_handler(self, *args, **kw):
t_data = kw.pop('data', '')
context = self.GLOBAL_CONTEXT.copy()
context.update(kw)
context['_args'] = args
context['lang'] = utils.LocaleBorg().current_lang
for k in self._GLOBAL_CONTEXT_TRANSLATABLE:
context[k] = context[k](context['lang'])
output = self.template_system.render_template_to_string(t_data, context)
# XXX FIXME: we have no standard way to get dependency information from
# a template that's not a file
dependencies = []
return output, dependencies

def register_shortcode(self, name, f):
"""Register function f to handle shortcode "name"."""
if name in self.shortcode_registry:
Expand Down

0 comments on commit acd6db1

Please sign in to comment.