J
J
jslby2020-08-02 04:33:26
Python
jslby, 2020-08-02 04:33:26

How to write a simple Jinja2 extension?

I'm trying to write a simple extension at the level of recoding all content to base64, but it doesn't work. I don't understand where is the error:

class Base64Extension(Extension):
  tags = {'base64'}

  def __init__(self, environment):
    super(Base64Extension, self).__init__(environment)

  def parse(self, parser):
    lineno = next(parser.stream).lineno
    args = [parser.parse_expression()]
    call = self.call_method('_render', args)
    return nodes.Output([call], lineno=lineno)

  def _render(self, text):
    return base64.b64encode(bytes(text, 'utf-8')).decode('utf-8')

env = Environment(loader=FileSystemLoader('project/test'), extensions=[Base64Extension], trim_blocks=True,block_start_string='',variable_start_string='[', variable_end_string=']')


print(env.get_template('data2.txt').render())


The template also looks very simple:
[base64]
Привет текста.
[endbase64]


The output is just text without tags. There are no simple examples of writing your own extensions, maybe someone has examples for example uppercase or the same base64?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question