How to use Jinja2 - 10 common examples

To help you get started, we’ve selected a few Jinja2 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github kamalgill / flask-appengine-template / src / lib / flask / testsuite / blueprints.py View on Github external
self.assert_equal(rv.data, b'Hello from the Admin')
        rv = c.get('/admin/static/test.txt')
        self.assert_equal(rv.data.strip(), b'Admin File')
        rv.close()
        rv = c.get('/admin/static/css/test.css')
        self.assert_equal(rv.data.strip(), b'/* nested file */')
        rv.close()

        with app.test_request_context():
            self.assert_equal(flask.url_for('admin.static', filename='test.txt'),
                              '/admin/static/test.txt')

        with app.test_request_context():
            try:
                flask.render_template('missing.html')
            except TemplateNotFound as e:
                self.assert_equal(e.name, 'missing.html')
            else:
                self.assert_true(0, 'expected exception')

        with flask.Flask(__name__).test_request_context():
            self.assert_equal(flask.render_template('nested/nested.txt'), 'I\'m nested')
github joerick / cibuildwheel / test / test_projects / c.py View on Github external
def new_c_project(*, spam_c_top_level_add='', spam_c_function_add='', setup_py_add='',
                  setup_py_setup_args_add='', setup_cfg_add=''):
    project = TestProject()

    project.files.update({
        'spam.c': jinja2.Template(SPAM_C_TEMPLATE),
        'setup.py': jinja2.Template(SETUP_PY_TEMPLATE),
        'setup.cfg': jinja2.Template(SETUP_CFG_TEMPLATE),
    })

    project.template_context.update({
        'spam_c_top_level_add': spam_c_top_level_add,
        'spam_c_function_add': spam_c_function_add,
        'setup_py_add': setup_py_add,
        'setup_py_setup_args_add': setup_py_setup_args_add,
        'setup_cfg_add': setup_cfg_add,
    })

    return project
github splunk / splunk-ref-pas-test / pas_simulated_users_addon / user-api / lib / jinja2 / parser.py View on Github external
elif token.value in ('none', 'None'):
                node = nodes.Const(None, lineno=token.lineno)
            else:
                node = nodes.Name(token.value, 'load', lineno=token.lineno)
            next(self.stream)
        elif token.type == 'string':
            next(self.stream)
            buf = [token.value]
            lineno = token.lineno
            while self.stream.current.type == 'string':
                buf.append(self.stream.current.value)
                next(self.stream)
            node = nodes.Const(''.join(buf), lineno=lineno)
        elif token.type in ('integer', 'float'):
            next(self.stream)
            node = nodes.Const(token.value, lineno=token.lineno)
        elif token.type == 'lparen':
            next(self.stream)
            node = self.parse_tuple(explicit_parentheses=True)
            self.stream.expect('rparen')
        elif token.type == 'lbracket':
            node = self.parse_list()
        elif token.type == 'lbrace':
            node = self.parse_dict()
        else:
            self.fail("unexpected '%s'" % describe_token(token), token.lineno)
        return node
github trailofbits / cb-multios / cqe-challenges / NRFIN_00007 / support / mixcodegen / jinja2 / tests.py View on Github external
def test_lower(value):
    """Return true if the variable is lowercased."""
    return text_type(value).islower()
github pallets / jinja / tests / test_nativetypes.py View on Github external
def test_string_literal_var(env):
    t = env.from_string("[{{ 'all' }}]")
    result = t.render()
    assert isinstance(result, text_type)
    assert result == "[all]"
github EUDAT-B2SHARE / b2share / simplestore / etc / uitestframe.py View on Github external
script tags (e.g. {% css ... %}, {% js ...%}).
		"""
		tag = parser.stream.current.value
		lineno = next(parser.stream).lineno

		default_bundle_name = u"%s" % (self.environment.default_bundle_name)
		default_bundle_name.encode('utf-8')
		bundle_name = nodes.Const(default_bundle_name)

		#parse filename
		if parser.stream.current.type != 'block_end':
			value = parser.parse_expression()
			# get first optional argument: bundle_name
			if parser.stream.skip_if('comma'):
				bundle_name = parser.parse_expression()
				if isinstance(bundle_name, nodes.Name):
					bundle_name = nodes.Name(bundle_name.name, 'load')
		else:
			value = parser.parse_tuple()

		args = [nodes.Const(tag), value, bundle_name]

		# Return html tag with link to corresponding script file.
		if self.environment.use_bundle is False:
			value = value.value
			if callable(self.environment.collection_templates[tag]):
				node = self.environment.collection_templates[tag](value)
			else:
				node = self.environment.collection_templates[tag] % value
			return nodes.Output([nodes.MarkSafeIfAutoescape(nodes.Const(node))])

		# Call :meth:`_update` to collect names of used scripts.
github splunk / splunk-ref-pas-test / pas_simulated_users_addon / user-api / lib / jinja2 / environment.py View on Github external
.. versionadded:: 2.1
        """
        parser = Parser(self, source, state='variable')
        exc_info = None
        try:
            expr = parser.parse_expression()
            if not parser.stream.eos:
                raise TemplateSyntaxError('chunk after expression',
                                          parser.stream.current.lineno,
                                          None, None)
            expr.set_environment(self)
        except TemplateSyntaxError:
            exc_info = sys.exc_info()
        if exc_info is not None:
            self.handle_exception(exc_info, source_hint=source)
        body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]
        template = self.from_string(nodes.Template(body, lineno=1))
        return TemplateExpression(template, undefined_to_none)
github splunk / splunk-ref-pas-test / pas_simulated_users_addon / user-api / lib / jinja2 / parser.py View on Github external
def parse_primary(self):
        token = self.stream.current
        if token.type == 'name':
            if token.value in ('true', 'false', 'True', 'False'):
                node = nodes.Const(token.value in ('true', 'True'),
                                   lineno=token.lineno)
            elif token.value in ('none', 'None'):
                node = nodes.Const(None, lineno=token.lineno)
            else:
                node = nodes.Name(token.value, 'load', lineno=token.lineno)
            next(self.stream)
        elif token.type == 'string':
            next(self.stream)
            buf = [token.value]
            lineno = token.lineno
            while self.stream.current.type == 'string':
                buf.append(self.stream.current.value)
                next(self.stream)
            node = nodes.Const(''.join(buf), lineno=lineno)
        elif token.type in ('integer', 'float'):
            next(self.stream)
            node = nodes.Const(token.value, lineno=token.lineno)
        elif token.type == 'lparen':
            next(self.stream)
            node = self.parse_tuple(explicit_parentheses=True)
            self.stream.expect('rparen')
github splunk / splunk-ref-pas-test / pas_simulated_users_addon / user-api / lib / jinja2 / compiler.py View on Github external
def pop_scope(self, aliases, frame):
        """Restore all aliases and delete unused variables."""
        for name, alias in iteritems(aliases):
            self.writeline('l_%s = %s' % (name, alias))
        to_delete = set()
        for name in frame.identifiers.declared_locally:
            if name not in aliases:
                to_delete.add('l_' + name)
        if to_delete:
            # we cannot use the del statement here because enclosed
            # scopes can trigger a SyntaxError:
            #   a = 42; b = lambda: a; del a
            self.writeline(' = '.join(to_delete) + ' = missing')
github google / clusterfuzz / src / appengine / handlers / testcase_detail / show.py View on Github external
def convert_to_lines(raw_stacktrace, crash_state_lines, crash_type):
  """Convert an array of string to an array of Line."""
  if not raw_stacktrace or not raw_stacktrace.strip():
    return []

  raw_lines = raw_stacktrace.splitlines()

  frames = get_stack_frames(crash_state_lines)
  escaped_frames = [jinja2.escape(f) for f in frames]
  combined_frames = frames + escaped_frames

  # Certain crash types have their own customized frames that are not related to
  # the stacktrace. Therefore, we make our best effort to preview stacktrace
  # in a reasonable way; we preview around the the top of the stacktrace.
  for unique_type in data_types.CRASH_TYPES_WITH_UNIQUE_STATE:
    if crash_type.startswith(unique_type):
      combined_frames = ['ERROR']
      break

  lines = []
  for index, content in enumerate(raw_lines):
    important = _is_line_important(content, combined_frames)
    lines.append(Line(index + 1, content, important))
  return lines