Я создаю расширение Jinja для Django.
Это выглядит примерно так:
class FieldObjectExtension(jinja2.ext.Extension):
"""A custom extension to render different objects fields."""
"""The tags this extension will parse."""
tags = {'fieldobj'}
def parse(self, parser):
lineno = next(parser.stream).lineno
args = [parser.parse_expression()]
# If there is a comma, the user provided a field type. If not use
# None as second parameter.
if parser.stream.skip_if('comma'):
args.append(parser.parse_expression())
else:
args.append(jinja2.nodes.Const(None))
call = self.call_method('_create_field', args) # <== I want to access this args argument ins
return jinja2.nodes.CallBlock(call, [], [], '').set_lineno(lineno)
def _create_field(self, name, caller):
"""Gets the field type and creates the HTML tag from it."""
if args == "textField": # <== Here I where I want to have access to args
html = f'<input type="text">'
elif args == "textArea":
html = f'<textarea></textarea>'
return html
Я хочу получить доступ к параметрам, хранящимся в args
, из _create_field
функция. Например, если я напишу {% fieldobj "textField" %}
, функция _create_field
получит строку textField
.
Я пробовал несколько способов, но получал всевозможные ошибки.