@ -23,38 +23,50 @@ def _escape_tex(value):
newval = pattern . sub ( replacement , newval )
return newval
class TexRenderer ( object ) :
""" Render a template to a LaTeX file. """
def _init_tex_env ( datadir = ' ' ) :
''' Start a new jinja2 environment for .tex creation '''
loader = ChoiceLoader ( [
PackageLoader ( ' songbook_core ' , ' data/templates ' ) ,
FileSystemLoader ( os . path . join ( datadir , ' templates ' ) ) ,
] )
texenv = Environment ( loader = loader )
texenv . block_start_string = ' (* '
texenv . block_end_string = ' *) '
texenv . variable_start_string = ' (( '
texenv . variable_end_string = ' )) '
texenv . comment_start_string = ' ( % c omment % ) '
texenv . comment_end_string = ' ( % e ndcomment % ) '
texenv . filters [ ' escape_tex ' ] = _escape_tex
texenv . trim_blocks = True
texenv . lstrip_blocks = True
return texenv
def render_tex ( output , context , datadir = ' ' ) :
''' Render a template into a .tex file
Arguments :
- output : a file object to write the result
- context : all the data to populate the template
- datadir : location of the user - defined templates
'''
env = _init_tex_env ( datadir = datadir )
template = env . get_template ( context [ ' template ' ] )
content = template . render ( * * context ) #pylint: disable=star-args
output . write ( content )
return None
def __init__ ( self , template , datadir = ' ' ) :
''' Start a new jinja2 environment for .tex creation.
Arguments :
- datadir : location of the user - defined templates
'''
self . template = template
self . texenv = Environment (
loader = ChoiceLoader ( [
FileSystemLoader (
os . path . join ( datadir , ' templates ' )
) ,
PackageLoader (
' songbook_core ' , os . path . join ( ' data ' , ' templates ' )
) ,
] )
)
self . texenv . block_start_string = ' (* '
self . texenv . block_end_string = ' *) '
self . texenv . variable_start_string = ' (( '
self . texenv . variable_end_string = ' )) '
self . texenv . comment_start_string = ' ( % c omment % ) '
self . texenv . comment_end_string = ' ( % e ndcomment % ) '
self . texenv . filters [ ' escape_tex ' ] = _escape_tex
self . texenv . trim_blocks = True
self . texenv . lstrip_blocks = True
def file_template ( self ) :
""" Return the filename of the selected template. """
return self . texenv . get_template ( self . template ) . filename
def render_tex ( self , output , context ) :
''' Render a template into a .tex file
Arguments :
- output : a file object to write the result
- context : all the data to populate the template
'''
#pylint: disable=star-args
output . write (
self . texenv . get_template ( self . template ) . render ( * * context )
)