def do_include_block(parser, token):
    """
        Works like the {% include <template_name> %} django templatetag,
        but additionally allows for definition of inline blocks that can be
        referenced in the included template.
        Usage:

            {% includeblock 'example/includable_template.html' <...> %}
                {% block myblock %}
                    <p>An inner block. Reference this using {{ myblock }} in the included template!</p>
                {% endblock myblock %}
                <b>This content is never rendered because it appears outside inner blocks!</b>
            {% endincludeblock %}
    """
    # inherit behaviour form ``include`` templatetag
    include_node = do_include(parser, token)

    # we give the parser a new "context" of blocks encountered in the inner includeblock,
    # so duplicate blocks don't cause a TemplateSyntaxError
    loaded_blocks = None
    if hasattr(parser, '__loaded_blocks'):
        loaded_blocks = copy(parser.__loaded_blocks)
        parser.__loaded_blocks = []
    nodelist = parser.parse(('endincludeblock',))

    if loaded_blocks is not None:
        parser.__loaded_blocks = loaded_blocks

    parser.delete_first_token()
    return IncludeBlockNode(nodelist, include_node)
def do_include_strip(parser, token):
    result = do_include(parser, token)
    if isinstance(result, ConstantIncludeNode):
        result.__class__ = StripConstantIncludeNode
    elif isinstance(result, IncludeNode):
        result.__class__ = StripIncludeNode
    return result
Exemplo n.º 3
0
def do_include_maybe(parser, token):
    """
    A template helper to optionally include a template partial, and catch the
    exception if it fails.
    Source: http://stackoverflow.com/a/18951166/15690
    """
    bits = token.split_contents()
    if len(bits) < 2:
        raise template.TemplateSyntaxError(
            "%r tag takes at least one argument: "
            "the name of the template to be included." % bits[0])

    try:
        silent_node = do_include(parser, token)
    except template.TemplateDoesNotExist:
        # Django < 1.7
        return CommentNode()

    _orig_render = silent_node.render

    def wrapped_render(*args, **kwargs):
        try:
            return _orig_render(*args, **kwargs)
        except template.TemplateDoesNotExist:
            return CommentNode()

    silent_node.render = wrapped_render
    return silent_node
def do_include_block(parser, token):
    """
        Works like the {% include <template_name> %} django templatetag,
        but additionally allows for definition of inline blocks that can be
        referenced in the included template.
        Usage:

            {% includeblock 'example/includable_template.html' <...> %}
                {% block myblock %}
                    <p>An inner block. Reference this using {{ myblock }} in the included template!</p>
                {% endblock myblock %}
                <b>This content is never rendered because it appears outside inner blocks!</b>
            {% endincludeblock %}
    """
    # inherit behaviour form ``include`` templatetag
    include_node = do_include(parser, token)

    # we give the parser a new "context" of blocks encountered in the inner includeblock,
    # so duplicate blocks don't cause a TemplateSyntaxError
    loaded_blocks = None
    if hasattr(parser, '__loaded_blocks'):
        loaded_blocks = copy(parser.__loaded_blocks)
        parser.__loaded_blocks = []
    nodelist = parser.parse(('endincludeblock', ))

    if loaded_blocks is not None:
        parser.__loaded_blocks = loaded_blocks

    parser.delete_first_token()
    return IncludeBlockNode(nodelist, include_node)
Exemplo n.º 5
0
def do_include_strip(parser, token):
    result = do_include(parser, token)
    if isinstance(result, ConstantIncludeNode):
        result.__class__ = StripConstantIncludeNode
    elif isinstance(result, IncludeNode):
        result.__class__ = StripIncludeNode
    return result
Exemplo n.º 6
0
def include_aware_block(parser, token):
    """
    this overrides {% include %} to keep track of whether the current template
    render context is in an include block
    """
    node = loader_tags.do_include(parser, token)
    node.__class__ = IncludeAwareNode
    return node
Exemplo n.º 7
0
def spaceless_include(parser, token):
    node = do_include(parser, token)
    args_dict = {
        "extra_context": node.extra_context,
        "isolated_context": node.isolated_context,
        "template": node.template,
    }
    return SpacelessIncludeNode(**args_dict)
Exemplo n.º 8
0
def include_aware_block(parser, token):
    """
    this overrides {% include %} to keep track of whether the current template
    render context is in an include block
    """
    node = loader_tags.do_include(parser, token)
    node.__class__ = IncludeAwareNode
    return node
Exemplo n.º 9
0
def frag_include(parser, token):

    _name = token.contents[token.contents.find("\"") +
                           1:token.contents.rfind("\"")]

    token.contents = 'include "fragments/{}.{}"'.format(
        _name, settings.TEMPLATE_EXTENSION)

    return do_include(parser, token)
Exemplo n.º 10
0
def include_(parser, token):
    """Similar to built-in ``include`` template tag, but allowing
    template variables to be used in template name and a fallback template,
    thus making the tag more dynamic.

    .. warning:: Requires Django 1.8+

    Example:

        {% load etc_misc %}
        {% include_ "sub_{{ postfix_var }}.html" fallback "default.html" %}

    """
    bits = token.split_contents()

    dynamic = False

    # We fallback to built-in `include` if a template name contains no variables.
    if len(bits) >= 2:
        dynamic = '{{' in bits[1]

        if dynamic:
            fallback = None
            bits_new = []

            for bit in bits:

                if fallback is True:
                    # This bit is a `fallback` argument.
                    fallback = bit
                    continue

                if bit == 'fallback':
                    fallback = True

                else:
                    bits_new.append(bit)

            if fallback:
                fallback = parser.compile_filter(
                    construct_relative_path_(parser, fallback))

            token.contents = ' '.join(bits_new)

    token.contents = token.contents.replace('include_', 'include')
    include_node = do_include(parser, token)

    if dynamic:
        # swap simple include with dynamic
        include_node = DynamicIncludeNode(
            include_node.template,
            extra_context=include_node.extra_context,
            isolated_context=include_node.isolated_context,
            fallback=fallback or None,
        )

    return include_node
Exemplo n.º 11
0
def include_(parser, token):
    """Similar to built-in ``include`` template tag, but allowing
    template variables to be used in template name and a fallback template,
    thus making the tag more dynamic.

    .. warning:: Requires Django 1.8+

    Example:

        {% load etc_misc %}
        {% include_ "sub_{{ postfix_var }}.html" fallback "default.html" %}

    """
    bits = token.split_contents()

    dynamic = False

    # We fallback to built-in `include` if a template name contains no variables.
    if len(bits) >= 2:
        dynamic = '{{' in bits[1]

        if dynamic:
            fallback = None
            bits_new = []

            for bit in bits:

                if fallback is True:
                    # This bit is a `fallback` argument.
                    fallback = bit
                    continue

                if bit == 'fallback':
                    fallback = True

                else:
                    bits_new.append(bit)

            if fallback:
                fallback = parser.compile_filter(construct_relative_path_(parser, fallback))

            token.contents = ' '.join(bits_new)

    token.contents = token.contents.replace('include_', 'include')
    include_node = do_include(parser, token)

    if dynamic:
        # swap simple include with dynamic
        include_node = DynamicIncludeNode(
            include_node.template,
            extra_context=include_node.extra_context,
            isolated_context=include_node.isolated_context,
            fallback=fallback or None,
        )

    return include_node
Exemplo n.º 12
0
def do_wrapwith(parser, token):
    """
    Calls the do_include function, but injects the contents of the block into
    the extra_context of the included template.
    """
    include_node = do_include(parser, token)
    nodelist = parser.parse(("endwrapwith", ))
    parser.delete_first_token()
    include_node.template = ResolveWithAliases(include_node.template)
    include_node.extra_context["wrapped"] = RenderNodelistVariable(nodelist)
    return include_node
Exemplo n.º 13
0
def do_include_stripped(parser, token):
    """Include template -- exactly as "include" -- but with leading &
    trailing white space stripped.

    Particularly useful for inclusion templates intended to render
    compact node attribute values (rather than markup).

    """
    include_node = loader_tags.do_include(parser, token)
    include_node.__class__ = IncludeStrippedNode
    return include_node
Exemplo n.º 14
0
def do_include(parser, token):
	try:
		nodelist = parser.parse(('endinclude',))
	except:
		return loader_tags.do_include(parser, token)
	
	partnodes = nodelist.get_nodes_by_type(PartNode)
	
	bits = token.split_contents()
	path = bits[1][1:-1] #always string, delete quotes
	
	parser.delete_first_token()
	return IncludeNode(partnodes, path)
Exemplo n.º 15
0
    def render(self, context):
        try:
            words = self.token.split_contents()
            variant = context.get(self.token.contents.split()[1],
                                  self.token.contents.split()[1])

            path = context.template_name
            parts = splitext(path)
            words[1] = f"'{parts[0]}_{variant}{parts[1]}'"

            include = do_include(self.parser,
                                 Token(self.token.token_type, " ".join(words)))
            return include.render(context)
        except template.TemplateDoesNotExist:
            return ''
        except Exception as e:  # @UnusedVariable
            return "!!!INCLUDE ERROR!!!"
Exemplo n.º 16
0
def do_embed(parser, token):
    include_node = do_include(parser, token)

    # Briefly forget about previously seen blocks, to ignore duplicates
    try:
        old_loaded_blocks = parser.__loaded_blocks
    except AttributeError:  # parser.__loaded_blocks isn't a list yet
        old_loaded_blocks = []
    parser.__loaded_blocks = []

    nodelist = parser.parse(('endembed',))
    endembed = parser.next_token()
    if endembed.contents != 'endembed':
        parser.invalid_block_tag(endembed, 'endembed', 'endembed')

    parser.__loaded_blocks = old_loaded_blocks

    return EmbedNode(nodelist, include_node)
Exemplo n.º 17
0
def do_include_kfm(parser, token):
    """
    テンプレートフォルダに存在する Kawaz Flavored Markdown ファイルを読み込み
    レンダリングするテンプレートタグ

    Usage:

        {% include_kfm "markdown/about.md" %}

    """
    def parse_kfm_decorator(fn):
        @wraps(fn)
        def render(*args, **kwargs):
            rendered = fn(*args, **kwargs)
            return parse_kfm(rendered)
        return render
    node = do_include(parser, token)
    node.render = parse_kfm_decorator(node.render)
    return node
Exemplo n.º 18
0
def do_include_once(parser, token):
    import types
    from django.template.loader_tags import (do_include,
                                             ConstantIncludeNode,
                                             IncludeNode)
    included = do_include(parser, token)
    
    if isinstance(included, ConstantIncludeNode):
        try:
            included.include_path = included.template.name
        except:
            included.include_path = None
    elif isinstance(included, IncludeNode):
        included.include_path = included.template_name
    else:
        included.include_path = None
    
    included._render_origin = included.render
    included.render = types.MethodType(render_include_once, included)
    return included
Exemplo n.º 19
0
def do_include_kfm(parser, token):
    """
    テンプレートフォルダに存在する Kawaz Flavored Markdown ファイルを読み込み
    レンダリングするテンプレートタグ

    Usage:

        {% include_kfm "markdown/about.md" %}

    """
    def parse_kfm_decorator(fn):
        @wraps(fn)
        def render(*args, **kwargs):
            rendered = fn(*args, **kwargs)
            return parse_kfm(rendered)

        return render

    node = do_include(parser, token)
    node.render = parse_kfm_decorator(node.render)
    return node
Exemplo n.º 20
0
def do_try_include(parser, token):
    "Source: http://stackoverflow.com/a/18951166/15690"
    bits = token.split_contents()
    if len(bits) < 2:
        raise template.TemplateSyntaxError(
            "%r tag takes at least one argument: "
            "the name of the template to be included." % bits[0])

    try:
        silent_node = do_include(parser, token)
    except template.TemplateDoesNotExist:
        # Django < 1.7
        return ""

    _orig_render = silent_node.render
    def wrapped_render(*args, **kwargs):
        try:
            return _orig_render(*args, **kwargs)
        except template.TemplateDoesNotExist:
            return ""
    silent_node.render = wrapped_render
    return silent_node
Exemplo n.º 21
0
def do_include_if_exists(parser, token):
    bits = token.split_contents()
    if len(bits) < 2:
        raise template.TemplateSyntaxError(
            "%r tag takes at least one argument: "
            "the name of the template to be included." % bits[0])

    try:
        silent_node = do_include(parser, token)
    except template.TemplateDoesNotExist:
        #return CommentNode()
        return ''

    _orig_render = silent_node.render
    def wrapped_render(*args, **kwargs):
        try:
            return _orig_render(*args, **kwargs)
        except template.TemplateDoesNotExist:
            #return CommentNode()
            return ''
    silent_node.render = wrapped_render
    return silent_node
Exemplo n.º 22
0
def deprecate_and_include(parser, token):
    """
    Raises a deprecation warning about using the first argument. The
    remaining arguments are passed to an ``{% include %}`` tag. Usage::

        {% deprecate_and_include "old_template.html" "new_template.html" %}

    In order to avoid re-implementing {% include %} so as to resolve variables,
    this tag currently only works with literal template path strings.
    """
    split_contents = token.split_contents()
    current_template = split_contents[1]
    new_template = split_contents[2]
    if settings.DEBUG:
        warnings.simplefilter('always', DeprecationWarning)
    warnings.warn("The %s template is deprecated; Use %s instead." %
                  (current_template, new_template),
                  DeprecationWarning,
                  stacklevel=2)
    new_contents = [split_contents[0]] + split_contents[2:]
    include_token = Token(token.token_type, " ".join(new_contents))

    return do_include(parser, include_token)
Exemplo n.º 23
0
def do_include_maybe(parser, token):
    "Source: http://stackoverflow.com/a/18951166/15690"
    bits = token.split_contents()
    if len(bits) < 2:
        raise template.TemplateSyntaxError(
            "%r tag takes at least one argument: "
            "the name of the template to be included." % bits[0])

    try:
        silent_node = do_include(parser, token)
    except template.TemplateDoesNotExist:
        # Django < 1.7
        return CommentNode()

    _orig_render = silent_node.render

    def wrapped_render(*args, **kwargs):
        try:
            return _orig_render(*args, **kwargs)
        except template.TemplateDoesNotExist:
            return CommentNode()
    silent_node.render = wrapped_render
    return silent_node
Exemplo n.º 24
0
def do_include_maybe(parser, token):
    try:
        return do_include(parser, token)
    except template.TemplateDoesNotExist:
        return CommentNode()
Exemplo n.º 25
0
 def __init__(self, parser, token):
     self.include_node = do_include(parser, token)
Exemplo n.º 26
0
def frag_include(parser, token):

    token.contents = 'components/{}.{}'.format(token.contents,
                                               settings.TEMPLATE_EXTENSION)

    return do_include(parser, token)
Exemplo n.º 27
0
def do_include_strip(parser, token):
    result = do_include(parser, token)
    result.__class__ = StripIncludeNode
    return result
Exemplo n.º 28
0
def dev_include(parser, token):

    if not settings.HAML_COMPILE:
        token.contents = token.contents.replace('.haml', '.html')

    return do_include(parser, token)
Exemplo n.º 29
0
def do_include_as_js_str(parser, token):
    return IncludeAsJsStrNode(do_include(parser, token))
Exemplo n.º 30
0
 def __init__(self, parser, token):
     self.include_node = do_include(parser, token)
Exemplo n.º 31
0
 def compilation_function(parser, token):
     returned_node = do_include(parser, token)
     return node_klass(returned_node)
Exemplo n.º 32
0
def includetext(parser, token):
    return IncludeTextNode(do_include(parser, token))
Exemplo n.º 33
0
def do_include_if_exists(parser, token):
    try:
        return do_include(parser, token)
    except template.TemplateDoesNotExist:
        return CommentNode()
Exemplo n.º 34
0
def do_include_strip(parser, token):
    result = do_include(parser, token)
    result.__class__ = StripIncludeNode
    return result
Exemplo n.º 35
0
def includetext(parser, token):
      return IncludeTextNode(do_include(parser, token))
 def compilation_function(parser, token):
     returned_node = do_include(parser, token)
     return node_klass(returned_node)