Python django.template.Node() Examples

The following are 25 code examples of django.template.Node(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.template , or try the search function .
Example #1
Source File: static.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def handle_token(cls, parser, token):
        """
        Class method to parse prefix node and return a Node.
        """
        bits = token.split_contents()

        if len(bits) < 2:
            raise template.TemplateSyntaxError(
                "'%s' takes at least one argument (path to file)" % bits[0])

        path = parser.compile_filter(bits[1])

        if len(bits) >= 2 and bits[-2] == 'as':
            varname = bits[3]
        else:
            varname = None

        return cls(varname, path) 
Example #2
Source File: template.py    From canvas with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def context_tag(self, func):
        params, xx, xxx, defaults = getargspec(func)

        class ContextNode(django_template.Node):
            def __init__(self, vars_to_resolve):
                self.vars_to_resolve = map(django_template.Variable, vars_to_resolve)

            def render(self, context):
                resolved_vars = [var.resolve(context) for var in self.vars_to_resolve]
                return func(context, *resolved_vars)

        compile_func = curry(django_template.generic_tag_compiler,
                             params[1:],
                             defaults[1:] if defaults else None,
                             getattr(func, "_decorated_function", func).__name__,
                             ContextNode)

        compile_func.__doc__ = func.__doc__

        self.tag(getattr(func, "_decorated_function", func).__name__, compile_func)
        return func 
Example #3
Source File: static.py    From bioforum with MIT License 6 votes vote down vote up
def handle_token(cls, parser, token):
        """
        Class method to parse prefix node and return a Node.
        """
        bits = token.split_contents()

        if len(bits) < 2:
            raise template.TemplateSyntaxError(
                "'%s' takes at least one argument (path to file)" % bits[0])

        path = parser.compile_filter(bits[1])

        if len(bits) >= 2 and bits[-2] == 'as':
            varname = bits[3]
        else:
            varname = None

        return cls(varname, path) 
Example #4
Source File: static.py    From python2017 with MIT License 6 votes vote down vote up
def handle_token(cls, parser, token):
        """
        Class method to parse prefix node and return a Node.
        """
        bits = token.split_contents()

        if len(bits) < 2:
            raise template.TemplateSyntaxError(
                "'%s' takes at least one argument (path to file)" % bits[0])

        path = parser.compile_filter(bits[1])

        if len(bits) >= 2 and bits[-2] == 'as':
            varname = bits[3]
        else:
            varname = None

        return cls(varname, path) 
Example #5
Source File: static.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def handle_token(cls, parser, token):
        """
        Class method to parse prefix node and return a Node.
        """
        bits = token.split_contents()

        if len(bits) < 2:
            raise template.TemplateSyntaxError(
                "'%s' takes at least one argument (path to file)" % bits[0])

        path = parser.compile_filter(bits[1])

        if len(bits) >= 2 and bits[-2] == 'as':
            varname = bits[3]
        else:
            varname = None

        return cls(varname, path) 
Example #6
Source File: static.py    From python with Apache License 2.0 6 votes vote down vote up
def handle_token(cls, parser, token):
        """
        Class method to parse prefix node and return a Node.
        """
        bits = token.split_contents()

        if len(bits) < 2:
            raise template.TemplateSyntaxError(
                "'%s' takes at least one argument (path to file)" % bits[0])

        path = parser.compile_filter(bits[1])

        if len(bits) >= 2 and bits[-2] == 'as':
            varname = bits[3]
        else:
            varname = None

        return cls(varname, path) 
Example #7
Source File: static.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def handle_token(cls, parser, token):
        """
        Class method to parse prefix node and return a Node.
        """
        bits = token.split_contents()

        if len(bits) < 2:
            raise template.TemplateSyntaxError(
                "'%s' takes at least one argument (path to file)" % bits[0])

        path = parser.compile_filter(bits[1])

        if len(bits) >= 2 and bits[-2] == 'as':
            varname = bits[3]
        else:
            varname = None

        return cls(varname, path) 
Example #8
Source File: static.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def handle_token(cls, parser, token):
        """
        Class method to parse prefix node and return a Node.
        """
        bits = token.split_contents()

        if len(bits) < 2:
            raise template.TemplateSyntaxError(
                "'%s' takes at least one argument (path to file)" % bits[0])

        path = parser.compile_filter(bits[1])

        if len(bits) >= 2 and bits[-2] == 'as':
            varname = bits[3]
        else:
            varname = None

        return cls(varname, path) 
Example #9
Source File: tethys_gizmos.py    From tethys with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def render(self, context):
        resolved_options = template.Variable(self.options).resolve(context)

        try:
            if self.gizmo_name is None or self.gizmo_name not in GIZMO_NAME_MAP:
                if hasattr(resolved_options, GIZMO_NAME_PROPERTY):
                    self._load_gizmo_name(resolved_options.gizmo_name)
                else:
                    raise TemplateSyntaxError('A valid gizmo name is required for this input format.')

            self._load_gizmos_rendered(context)

            # Derive path to gizmo template
            if self.gizmo_name not in EXTENSION_PATH_MAP:
                # Determine path to gizmo template
                gizmo_templates_root = os.path.join('tethys_gizmos', 'gizmos')

            else:
                gizmo_templates_root = os.path.join(EXTENSION_PATH_MAP[self.gizmo_name], 'templates', 'gizmos')

            gizmo_file_name = '{0}.html'.format(self.gizmo_name)
            template_name = os.path.join(gizmo_templates_root, gizmo_file_name)

            # reset gizmo_name in case Node is rendered with different options
            self._load_gizmo_name(None)

            # Retrieve the gizmo template and render
            t = get_template(template_name)
            return t.render(resolved_options)

        except Exception:
            if hasattr(settings, 'TEMPLATES'):
                for template_settings in settings.TEMPLATES:
                    if 'OPTIONS' in template_settings \
                            and 'debug' in template_settings['OPTIONS'] \
                            and template_settings['OPTIONS']['debug']:
                        raise
            return '' 
Example #10
Source File: static.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def handle_token(cls, parser, token, name):
        """
        Class method to parse prefix node and return a Node.
        """
        # token.split_contents() isn't useful here because tags using this method don't accept variable as arguments
        tokens = token.contents.split()
        if len(tokens) > 1 and tokens[1] != 'as':
            raise template.TemplateSyntaxError(
                "First argument in '%s' must be 'as'" % tokens[0])
        if len(tokens) > 1:
            varname = tokens[2]
        else:
            varname = None
        return cls(varname, name) 
Example #11
Source File: notification_helpers.py    From govready-q with GNU General Public License v3.0 5 votes vote down vote up
def render_markdown_instead_of_escaping(parser, token):
	class Node(template.Node):
		def __init__(self, variable_name):
			self.variable = template.Variable(variable_name)
		def render(self, context):
			md = self.variable.resolve(context)
			if not context.autoescape:
				# Auto-escaping is off, so we're in the text portion
				# of a notification email. Return the raw markdown.
				return md
			else:
				# Auto-escaping is on, so we're in the HTML portion
				# of a notification email. Rather than returning the
				# raw Markdown, which will look funny because e.g.
				# line breaks will be ignored when it is placed within
				# HTML, render the Markdown to HTML. Turn on safe mode
				# since the content can't be trusted.
				import commonmark
				return commonmark.HtmlRenderer({ "safe": True })\
					.render(commonmark.Parser().parse(md))
	try:
		tag_name, variable_name = token.split_contents()
	except ValueError:
		raise template.TemplateSyntaxError(
			"%r tag requires a single argument naming a variable" % token.contents.split()[0]
		)
	return Node(variable_name) 
Example #12
Source File: log.py    From python2017 with MIT License 5 votes vote down vote up
def __repr__(self):
        return "<GetAdminLog Node>" 
Example #13
Source File: static.py    From python2017 with MIT License 5 votes vote down vote up
def handle_token(cls, parser, token, name):
        """
        Class method to parse prefix node and return a Node.
        """
        # token.split_contents() isn't useful here because tags using this method don't accept variable as arguments
        tokens = token.contents.split()
        if len(tokens) > 1 and tokens[1] != 'as':
            raise template.TemplateSyntaxError(
                "First argument in '%s' must be 'as'" % tokens[0])
        if len(tokens) > 1:
            varname = tokens[2]
        else:
            varname = None
        return cls(varname, name) 
Example #14
Source File: log.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def __repr__(self):
        return "<GetAdminLog Node>" 
Example #15
Source File: static.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def handle_token(cls, parser, token, name):
        """
        Class method to parse prefix node and return a Node.
        """
        # token.split_contents() isn't useful here because tags using this method don't accept variable as arguments
        tokens = token.contents.split()
        if len(tokens) > 1 and tokens[1] != 'as':
            raise template.TemplateSyntaxError(
                "First argument in '%s' must be 'as'" % tokens[0])
        if len(tokens) > 1:
            varname = tokens[2]
        else:
            varname = None
        return cls(varname, name) 
Example #16
Source File: static.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def handle_token(cls, parser, token, name):
        """
        Class method to parse prefix node and return a Node.
        """
        tokens = token.contents.split()
        if len(tokens) > 1 and tokens[1] != 'as':
            raise template.TemplateSyntaxError(
                "First argument in '%s' must be 'as'" % tokens[0])
        if len(tokens) > 1:
            varname = tokens[2]
        else:
            varname = None
        return cls(varname, name) 
Example #17
Source File: log.py    From python with Apache License 2.0 5 votes vote down vote up
def __repr__(self):
        return "<GetAdminLog Node>" 
Example #18
Source File: static.py    From python with Apache License 2.0 5 votes vote down vote up
def handle_token(cls, parser, token, name):
        """
        Class method to parse prefix node and return a Node.
        """
        # token.split_contents() isn't useful here because tags using this method don't accept variable as arguments
        tokens = token.contents.split()
        if len(tokens) > 1 and tokens[1] != 'as':
            raise template.TemplateSyntaxError(
                "First argument in '%s' must be 'as'" % tokens[0])
        if len(tokens) > 1:
            varname = tokens[2]
        else:
            varname = None
        return cls(varname, name) 
Example #19
Source File: log.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def __repr__(self):
        return "<GetAdminLog Node>" 
Example #20
Source File: static.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def handle_token(cls, parser, token, name):
        """
        Class method to parse prefix node and return a Node.
        """
        # token.split_contents() isn't useful here because tags using this method don't accept variable as arguments
        tokens = token.contents.split()
        if len(tokens) > 1 and tokens[1] != 'as':
            raise template.TemplateSyntaxError(
                "First argument in '%s' must be 'as'" % tokens[0])
        if len(tokens) > 1:
            varname = tokens[2]
        else:
            varname = None
        return cls(varname, name) 
Example #21
Source File: compat.py    From django-compat with MIT License 5 votes vote down vote up
def verbatim(parser, token):
    if django.VERSION >= (1, 5):
        from django.template.defaulttags import verbatim as verbatim_defaulttag
        return verbatim_defaulttag(parser, token)

    # 1.4; not available from django
    # Source: https://github.com/aljosa/django-verbatim
    class VerbatimNode(template.Node):
        def __init__(self, content):
            self.content = content

        def render(self, context):
            return self.content

    text = []
    while 1:
        token = parser.tokens.pop(0)
        if token.contents == 'endverbatim':
            break
        if token.token_type == template.TOKEN_VAR:
            text.append('{{ ')
        elif token.token_type == template.TOKEN_BLOCK:
            text.append('{% ')
        text.append(token.contents)
        if token.token_type == template.TOKEN_VAR:
            text.append(' }}')
        elif token.token_type == template.TOKEN_BLOCK:
            text.append(' %}')
    return VerbatimNode(''.join(text)) 
Example #22
Source File: log.py    From bioforum with MIT License 5 votes vote down vote up
def __repr__(self):
        return "<GetAdminLog Node>" 
Example #23
Source File: static.py    From bioforum with MIT License 5 votes vote down vote up
def handle_token(cls, parser, token, name):
        """
        Class method to parse prefix node and return a Node.
        """
        # token.split_contents() isn't useful here because tags using this method don't accept variable as arguments
        tokens = token.contents.split()
        if len(tokens) > 1 and tokens[1] != 'as':
            raise template.TemplateSyntaxError(
                "First argument in '%s' must be 'as'" % tokens[0])
        if len(tokens) > 1:
            varname = tokens[2]
        else:
            varname = None
        return cls(varname, name) 
Example #24
Source File: log.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def __repr__(self):
        return "<GetAdminLog Node>" 
Example #25
Source File: sql.py    From canvas with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def execute(self, sql, params=()):
        start = datetime.now()
        try:
            return self.cursor.execute(sql, params)
        finally:
            stop = datetime.now()
            duration = ms_from_timedelta(stop - start)
            stacktrace = tidy_stacktrace(traceback.extract_stack())
            _params = ''
            try:
                _params = simplejson.dumps([force_unicode(x, strings_only=True) for x in params])
            except TypeError:
                pass # object not JSON serializable

            template_info = None
            cur_frame = sys._getframe().f_back
            try:
                while cur_frame is not None:
                    if cur_frame.f_code.co_name == 'render':
                        node = cur_frame.f_locals['self']
                        if isinstance(node, Node):
                            template_info = get_template_info(node.source)
                            break
                    cur_frame = cur_frame.f_back
            except:
                pass
            del cur_frame

            # We keep `sql` to maintain backwards compatibility
            self.db.queries.append({
                'sql': self.db.ops.last_executed_query(self.cursor, sql, params),
                'duration': duration,
                'raw_sql': sql,
                'params': _params,
                'hash': sha_constructor(settings.SECRET_KEY + sql + _params).hexdigest(),
                'stacktrace': stacktrace,
                'start_time': start,
                'stop_time': stop,
                'is_slow': (duration > SQL_WARNING_THRESHOLD),
                'is_select': sql.lower().strip().startswith('select'),
                'template_info': template_info,
            })