Browse Source

Templates: Reorganise default filters

pull/176/head
Louis 9 years ago
parent
commit
0f2c0938bc
  1. 29
      patacrep/songs/chordpro/__init__.py
  2. 43
      patacrep/templates.py

29
patacrep/songs/chordpro/__init__.py

@ -14,7 +14,6 @@ from patacrep.songs.chordpro.syntax import parse_song
from patacrep.songs.errors import FileNotFound, SongUnknownLanguage from patacrep.songs.errors import FileNotFound, SongUnknownLanguage
from patacrep.templates import Renderer from patacrep.templates import Renderer
from patacrep.latex import lang2babel, UnknownLanguage from patacrep.latex import lang2babel, UnknownLanguage
from patacrep.files import path2posix
LOGGER = logging.getLogger(__name__) LOGGER = logging.getLogger(__name__)
@ -22,6 +21,10 @@ def sort_directive_argument(directives):
"""Sort directives by their argument.""" """Sort directives by their argument."""
return sorted(directives, key=operator.attrgetter("argument")) return sorted(directives, key=operator.attrgetter("argument"))
DEFAULT_FILTERS = {
'sortargs': sort_directive_argument,
}
class ChordproSong(Song): class ChordproSong(Song):
"""Chordpro song parser""" """Chordpro song parser"""
# pylint: disable=abstract-method # pylint: disable=abstract-method
@ -41,10 +44,14 @@ class ChordproSong(Song):
'song': song, 'song': song,
} }
@staticmethod def _filters(self):
def _jinja2_filters():
"""Return additional jinja2 filters.""" """Return additional jinja2 filters."""
return {} filters = DEFAULT_FILTERS.copy()
filters.update({
'search_image': self.search_image,
'search_partition': self.search_partition,
})
return filters
def render(self, template="song"): # pylint: disable=arguments-differ def render(self, template="song"): # pylint: disable=arguments-differ
context = { context = {
@ -59,11 +66,7 @@ class ChordproSong(Song):
jinjaenv = Environment(loader=FileSystemLoader( jinjaenv = Environment(loader=FileSystemLoader(
self.iter_datadirs("templates", "songs", "chordpro", self.output_language) self.iter_datadirs("templates", "songs", "chordpro", self.output_language)
)) ))
jinjaenv.filters['search_image'] = self.search_image jinjaenv.filters.update(self._filters())
jinjaenv.filters['search_partition'] = self.search_partition
jinjaenv.filters['sortargs'] = sort_directive_argument
jinjaenv.filters['path2posix'] = path2posix
jinjaenv.filters.update(self._jinja2_filters())
try: try:
return Renderer( return Renderer(
@ -132,10 +135,12 @@ class Chordpro2LatexSong(ChordproSong):
LOGGER.warning(message) LOGGER.warning(message)
return None return None
def _jinja2_filters(self): def _filters(self):
return { parent = super()._filters()
parent.update({
'lang2babel': self.lang2babel, 'lang2babel': self.lang2babel,
} })
return parent
def lang2babel(self, lang): def lang2babel(self, lang):
"""Return the LaTeX babel code corresponding to `lang`. """Return the LaTeX babel code corresponding to `lang`.

43
patacrep/templates.py

@ -45,6 +45,18 @@ _VARIABLE_REGEXP = re.compile(
""", """,
re.VERBOSE|re.DOTALL) re.VERBOSE|re.DOTALL)
def _escape_tex(value):
'''Escape TeX special characters'''
newval = value
for pattern, replacement in _LATEX_SUBS:
newval = pattern.sub(replacement, newval)
return newval
DEFAULT_FILTERS = {
"escape_tex": _escape_tex,
"iter_datadirs": files.iter_datadirs,
"path2posix": files.path2posix,
}
class VariablesExtension(Extension): class VariablesExtension(Extension):
"""Extension to jinja2 to silently ignore variable block. """Extension to jinja2 to silently ignore variable block.
@ -62,14 +74,6 @@ class VariablesExtension(Extension):
return nodes.Const("") # pylint: disable=no-value-for-parameter return nodes.Const("") # pylint: disable=no-value-for-parameter
def _escape_tex(value):
'''Escape TeX special characters'''
newval = value
for pattern, replacement in _LATEX_SUBS:
newval = pattern.sub(replacement, newval)
return newval
class Renderer: class Renderer:
"""Render a template to a LaTeX file.""" """Render a template to a LaTeX file."""
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
@ -85,22 +89,23 @@ class Renderer:
self.jinjaenv.comment_start_string = '(% comment %)' self.jinjaenv.comment_start_string = '(% comment %)'
self.jinjaenv.comment_end_string = '(% endcomment %)' self.jinjaenv.comment_end_string = '(% endcomment %)'
self.jinjaenv.line_comment_prefix = '%!' self.jinjaenv.line_comment_prefix = '%!'
self.jinjaenv.filters['escape_tex'] = _escape_tex
self.jinjaenv.trim_blocks = True self.jinjaenv.trim_blocks = True
self.jinjaenv.lstrip_blocks = True self.jinjaenv.lstrip_blocks = True
self._fill_filters() # Fill default filters
self.template = self.jinjaenv.get_template(template) for key, value in self.filters().items():
def _fill_filters(self):
"""Define some jinja2 filters, if not set yet."""
for key, value in [
("path2posix", files.path2posix),
("iter_datadirs", files.iter_datadirs),
("lang2babel", self.lang2babel),
]:
if key not in self.jinjaenv.filters: if key not in self.jinjaenv.filters:
self.jinjaenv.filters[key] = value self.jinjaenv.filters[key] = value
self.template = self.jinjaenv.get_template(template)
def filters(self):
"""Return a dictionary of jinja2 filters."""
filters = DEFAULT_FILTERS.copy()
filters.update({
"lang2babel": self.lang2babel,
})
return filters
def lang2babel(self, lang): def lang2babel(self, lang):
"""Return the LaTeX babel code corresponding to `lang`. """Return the LaTeX babel code corresponding to `lang`.

Loading…
Cancel
Save