MCPcopy
hub / github.com/django/django / Template

Class Template

django/template/base.py:141–291  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

139
140
141class Template:
142 def __init__(self, template_string, origin=None, name=None, engine=None):
143 # If Template is instantiated directly rather than from an Engine and
144 # exactly one Django template engine is configured, use that engine.
145 # This is required to preserve backwards-compatibility for direct use
146 # e.g. Template('...').render(Context({...}))
147 if engine is None:
148 from .engine import Engine
149
150 engine = Engine.get_default()
151 if origin is None:
152 origin = Origin(UNKNOWN_SOURCE)
153 self.name = name
154 self.origin = origin
155 self.engine = engine
156 self.source = str(template_string) # May be lazy.
157 self.nodelist = self.compile_nodelist()
158
159 def __repr__(self):
160 return '<%s template_string="%s...">' % (
161 self.__class__.__qualname__,
162 self.source[:20].replace("\n", ""),
163 )
164
165 def _render(self, context):
166 return self.nodelist.render(context)
167
168 def render(self, context):
169 "Display stage -- can be called many times"
170 with context.render_context.push_state(self):
171 if context.template is None:
172 with context.bind_template(self):
173 context.template_name = self.name
174 return self._render(context)
175 else:
176 return self._render(context)
177
178 def compile_nodelist(self):
179 """
180 Parse and compile the template source into a nodelist. If debug
181 is True and an exception occurs during parsing, the exception is
182 annotated with contextual line information where it occurred in the
183 template source.
184 """
185 if self.engine.debug:
186 lexer = DebugLexer(self.source)
187 else:
188 lexer = Lexer(self.source)
189
190 tokens = lexer.tokenize()
191 parser = Parser(
192 tokens,
193 self.engine.template_libraries,
194 self.engine.template_builtins,
195 self.origin,
196 )
197
198 try:

Calls

no outgoing calls