Function taking parsed template tag
    to a MacroBlockNode.
763073
def do_macro_block(parser, token):
    
    tag_name, macro_name, args, kwargs = parse_macro_params(token)
    # could add extra validation on the macro_name tag
    # here, but probably don't need to since we're checking
    # if there's a macro by that name anyway.
    try:
        # see if the macro is in the context.
        macro = parser._macros[macro_name]
    except (AttributeError, KeyError):
        raise template.TemplateSyntaxError(
            "Macro '{0}' is not defined ".format(macro_name) +
            "previously to the {0} tag".format(tag_name))
    # get the arg and kwarg nodes from the nodelist
    nodelist = parser.parse(('endmacro_block',))
    parser.delete_first_token()

    # Loop through nodes, sorting into args/kwargs
    # (we could do this more semantically, but we loop
    # only once like this as an optimization).
    for node in nodelist:
        if isinstance(node, MacroArgNode) and not isinstance(node, MacroKwargNode):
            # note that MacroKwargNode is also a MacroArgNode (via inheritance),
            # so we must check against this.
            args.append(node)
        elif isinstance(node, MacroKwargNode):
            if node.keyword in macro.kwargs:
                # check that the keyword is defined as an argument for
                # the macro.
                if node.keyword not in kwargs:
                    # add the keyword argument to the dict
                    # if it's not in there
                    kwargs[node.keyword] = node
                else:
                    # raise a template syntax error if the
                    # keyword is already in the dict (thus a keyword
                    # argument was passed twice.
                    raise template.TemplateSyntaxError(
                        "{0} template tag was supplied "
                        "the same keyword argument multiple times.".format(
                            tag_name))
            else:
                raise template.TemplateSyntaxError(
                    "{0} template tag was supplied with a "
                    "keyword argument not defined by the {1} macro.".format(
                        tag_name, macro_name))
        # The following is a check that only whitespace is inside the macro_block tag,
        # but it's currently removed for reasons of backwards compatibility/potential 
        # uses people might have to put extra stuff in te macro_block tag.
        # elif not isinstance(node, template.TextNode) or node.s.strip() != "":
        #     # whitespace is allowed, anything else is not
        #     raise template.TemplateSyntaxError(
        #         "{0} template tag received an argument that "
        #         "is neither a arg or a kwarg tag. Make sure there's "
        #         "text or template tags directly descending "
        #         "from the {0} tag.".format(tag_name))

    # check that there aren't more arg tags than args
    # in the macro.
    if len(args) > len(macro.args):
        raise template.TemplateSyntaxError(
            "{0} template tag was supplied too many arg block tags.".format(
                tag_name))

    macro.parser = parser
    return MacroBlockNode(macro, nodelist, args, kwargs)
1006142
def parse_template(template):
    """"""
    m = TEMPLATE_OVERRIDE_RE.match(template)
    if not m:
        return template, 0
    return m.group('template'), int(m.group('depth'))
1223490
function transformTemplateElement (node) {
    const originalValue = node.value.value.raw
    if (rootPathWithDotRegex.test(originalValue)) {
      node.value.value.raw = node.value.value.raw.replace(
        rootPathWithDotRegex,
        '$$$1'
      )
    }
  }
817364
def do_usemacro(parser, token):
    
    tag_name, macro_name, args, kwargs = parse_macro_params(token)
    try:
        macro = parser._macros[macro_name]
    except (AttributeError, KeyError):
        raise template.TemplateSyntaxError(
            "Macro '{0}' is not defined previously to the {1} tag".format(
                macro_name, tag_name))
    macro.parser = parser
    return UseMacroNode(macro, args, kwargs)
829392
function compile_fancy(block, scope) {
    var fns= block.toString().replace(css_matcher, function(src, tag_name, classes, hash, empty){
      var result= src.replace(classes, ''), tag_start,
          class_names= (classes || "").split(' ').join('').split('.').splice(1).join(' ');
      if(!tagset[tag_name]) {
        result= src;
      } else if(class_names !== "") {
        tag_start= tag_name +'({"class":"'+ class_names +'"';
        if(hash) {
          result= tag_start +', '+ result.substring((result.indexOf('{') + 1));
        } else if(empty) {
          result= tag_start +'})';
        } else {
          result= tag_start +'},'+ result.substring((result.indexOf('(') + 1));
        }
      } 
      return result;
    });
    return compile_scope(fns, scope);
  }
1332816
def parse_placeholder(parser, token):
    """"""
    params = {}

    bits = token.split_contents()
    count = len(bits)
    error_string = '%r tag requires at least one argument' % bits[0]
    if count <= 1:
        raise TemplateSyntaxError(error_string)
    try:
        name = unescape_string_literal(bits[1])
    except ValueError:
        name = bits[1]
    remaining = bits[2:]
    simple_options = ['parsed', 'inherited', 'untranslated', 'shared', 'block']
    param_options = ['as', 'on', 'with', 'section']
    all_options = simple_options + param_options
    while remaining:
        bit = remaining[0]
        if bit not in all_options:
            raise TemplateSyntaxError(
                "%r is not an correct option for a placeholder" % bit)
        if bit in param_options:
            if len(remaining) < 2:
                raise TemplateSyntaxError(
                    "Placeholder option '%s' need a parameter" % bit)
            if bit == 'as':
                params['as_varname'] = remaining[1]
            if bit == 'with':
                params['widget'] = remaining[1]
            if bit == 'on':
                params['page'] = remaining[1]
            if bit == 'section':
                params['section'] = unescape_string_literal(remaining[1])
            remaining = remaining[2:]
        elif bit == 'parsed':
            params['parsed'] = True
            remaining = remaining[1:]
        elif bit == 'inherited':
            params['inherited'] = True
            remaining = remaining[1:]
        elif bit == 'untranslated':
            params['untranslated'] = True
            remaining = remaining[1:]
        elif bit == 'shared':
            params['shared'] = True
            remaining = remaining[1:]
        elif bit == 'block':
            remaining = remaining[1:]
            nodelist = parser.parse(('endplaceholder',))
            parser.delete_first_token()
            params['nodelist'] = nodelist

    return name, params
285305
private void doSubstitutions(NodeTraversal t, Config config, Node n) {
    if (n.isTaggedTemplateLit()) {
      // This is currently not supported, since tagged template literals have a different calling
      // convention than ordinary functions, so it's unclear which arguments are expected to be
      // replaced. Specifically, there are no direct string arguments, and for arbitrary tag
      // functions it's not clear that it's safe to inline any constant placeholders.
      compiler.report(JSError.make(n, STRING_REPLACEMENT_TAGGED_TEMPLATE));
      return;
    }
    checkState(n.isNew() || n.isCall());

    if (!config.isReplaceAll()) {
      // Note: the first child is the function, but the parameter id is 1 based.
      for (int parameter : config.parameters) {
        Node arg = n.getChildAtIndex(parameter);
        if (arg != null) {
          replaceExpression(t, arg, n);
        }
      }
    } else {
      // Replace all parameters.
      Node firstParam = n.getSecondChild();
      for (Node arg = firstParam; arg != null; arg = arg.getNext()) {
        arg = replaceExpression(t, arg, n);
      }
    }
  }
1131597
def _Tokenize(template_str, meta_left, meta_right, whitespace):
    """"""
    
    trimlen = len(meta_left)
    token_re = MakeTokenRegex(meta_left, meta_right)
    do_strip = (whitespace == 'strip-line')  # Do this outside loop
    do_strip_part = False
    
    for line in template_str.splitlines(True):  # retain newlines
        if do_strip or do_strip_part:
            line = line.strip()
        
        tokens = token_re.split(line)
        
        # Check for a special case first.  If a comment or "block" directive is on a
        # line by itself (with only space surrounding it), then the space is
        # omitted.  For simplicity, we don't handle the case where we have 2
        # directives, say '{.end} # {#comment}' on a line.
        if len(tokens) == 3:
            # ''.isspace() == False, so work around that
            if (tokens[0].isspace() or not tokens[0]) and \
                    (tokens[2].isspace() or not tokens[2]):
                token = tokens[1][trimlen: -trimlen]
                
                # Check the ones that begin with ## before #
                if token == COMMENT_BEGIN:
                    yield COMMENT_BEGIN_TOKEN, None
                    continue
                if token == COMMENT_END:
                    yield COMMENT_END_TOKEN, None
                    continue
                if token == OPTION_STRIP_LINE:
                    do_strip_part = True
                    continue
                if token == OPTION_END:
                    do_strip_part = False
                    continue
                
                if token.startswith('#'):
                    continue  # The whole line is omitted
                
                token_type, token = _MatchDirective(token)
                if token_type is not None:
                    yield token_type, token  # Only yield the token, not space
                    continue
        
        # The line isn't special; process it normally.
        for i, token in enumerate(tokens):
            if i % 2 == 0:
                yield LITERAL_TOKEN, token
            
            else:  # It's a "directive" in metachracters
                assert token.startswith(meta_left), repr(token)
                assert token.endswith(meta_right), repr(token)
                token = token[trimlen: -trimlen]
                
                # Check the ones that begin with ## before #
                if token == COMMENT_BEGIN:
                    yield COMMENT_BEGIN_TOKEN, None
                    continue
                if token == COMMENT_END:
                    yield COMMENT_END_TOKEN, None
                    continue
                if token == OPTION_STRIP_LINE:
                    do_strip_part = True
                    continue
                if token == OPTION_END:
                    do_strip_part = False
                    continue
                
                # A single-line comment
                if token.startswith('#'):
                    continue
                
                if token.startswith('.'):
                    literal = {
                        '.meta-left': meta_left,
                        '.meta-right': meta_right,
                        '.space': ' ',
                        '.tab': '\t',
                        '.newline': '\n',
                    }.get(token)
                    
                    if literal is not None:
                        yield META_LITERAL_TOKEN, literal
                        continue
                    
                    token_type, token = _MatchDirective(token)
                    if token_type is not None:
                        yield token_type, token
                
                else:  # Now we know the directive is a substitution.
                    yield SUBST_TOKEN, token
906803
function t (template, data) {
    for (var key in data) {
      template = template.replace(new RegExp('{' + key + '}', 'g'), data[key] || '')
    }
    return template
  }
842009
def visit_Include(self, node, frame):
        """"""
        if node.ignore_missing:
            self.writeline('try:')
            self.indent()

        func_name = 'get_or_select_template'
        if isinstance(node.template, nodes.Const):
            if isinstance(node.template.value, string_types):
                func_name = 'get_template'
            elif isinstance(node.template.value, (tuple, list)):
                func_name = 'select_template'
        elif isinstance(node.template, (nodes.Tuple, nodes.List)):
            func_name = 'select_template'

        self.writeline('template = environment.%s(' % func_name, node)
        self.visit(node.template, frame)
        self.write(', %r)' % self.name)
        if node.ignore_missing:
            self.outdent()
            self.writeline('except TemplateNotFound:')
            self.indent()
            self.writeline('pass')
            self.outdent()
            self.writeline('else:')
            self.indent()

        skip_event_yield = False
        if node.with_context:
            loop = self.environment.is_async and 'async for' or 'for'
            self.writeline('%s event in template.root_render_func('
                           'template.new_context(context.get_all(), True, '
                           '%s)):' % (loop, self.dump_local_context(frame)))
        elif self.environment.is_async:
            self.writeline('for event in (await '
                           'template._get_default_module_async())'
                           '._body_stream:')
        else:
            if supports_yield_from:
                self.writeline('yield from template._get_default_module()'
                               '._body_stream')
                skip_event_yield = True
            else:
                self.writeline('for event in template._get_default_module()'
                               '._body_stream:')

        if not skip_event_yield:
            self.indent()
            self.simple_write('event', frame)
            self.outdent()

        if node.ignore_missing:
            self.outdent()
982782
private If parseIf(Node node) {
        return new If(
                nodeAttribute(node, TAG_VAR_ATTR_NAME, Variable.DEFAULT_NAME),
                parseTemplateElements(node)
        );
    }
1084457
def as_tag(self, tag_func):
        
        @wraps(tag_func)
        def tag_wrapper(parser, token):
            class AsTagNode(template.Node):
                def render(self, context):
                    parts = token.split_contents()

                    # Resolve variables if their names are given.
                    def resolve(arg):
                        try:
                            return template.Variable(arg).resolve(context)
                        except template.VariableDoesNotExist:
                            return arg
                    args, kwargs = [], {}
                    for arg in parts[1:-2]:
                        if "=" in arg:
                            name, val = arg.split("=", 1)
                            if name in tag_func.__code__.co_varnames:
                                kwargs[name] = resolve(val)
                                continue
                        args.append(resolve(arg))
                    context[parts[-1]] = tag_func(*args, **kwargs)
                    return ""
            return AsTagNode()
        return self.tag(tag_wrapper)
239734
function html($node, isNewlineOnBlock) {
  let markup = value($node);

  if (isNewlineOnBlock) {
    const regexTag = /<(\/?)(\b(?!!)[^>\s]*)(.*?)(\s*\/?>)/g;
    markup = markup.replace(regexTag, function(match, endSlash, name) {
      name = name.toUpperCase();
      const isEndOfInlineContainer = /^DIV|^TD|^TH|^P|^LI|^H[1-7]/.test(name) &&
                                   !!endSlash;
      const isBlockNode = /^BLOCKQUOTE|^TABLE|^TBODY|^TR|^HR|^UL|^OL/.test(name);

      return match + ((isEndOfInlineContainer || isBlockNode) ? '\n' : '');
    });
    markup = markup.trim();
  }

  return markup;
}
637063
def grab_literal(template, l_del):
    """"""

    global _CURRENT_LINE

    try:
        # Look for the next tag and move the template to it
        literal, template = template.split(l_del, 1)
        _CURRENT_LINE += literal.count('\n')
        return (literal, template)

    # There are no more tags in the template?
    except ValueError:
        # Then the rest of the template is a literal
        return (template, '')
22610
function templateNodeTransformation( $functionName, &$node,
                                         $tpl, $parameters, $privateData )
    {
        /*
        {foreach <array> as [$keyVar =>] $itemVar
                 [sequence <array> as $sequenceVar]
                 [offset <offset>]
                 [max <max>]
                 [reverse]
        }
        */

        $tpl->ForeachCounter++;
        $newNodes            = array();
        $nodePlacement       = eZTemplateNodeTool::extractFunctionNodePlacement( $node );
        $uniqid              =  md5( $nodePlacement[2] ) . "_" . $tpl->ForeachCounter;

        $loop = new eZTemplateCompiledLoop( eZTemplateForeachFunction::FUNCTION_NAME,
                                            $newNodes, $parameters, $nodePlacement, $uniqid,
                                            $node, $tpl, $privateData );



        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "// foreach begins" );

        $loop->initVars();

        $array           = "fe_array_$uniqid";
        $arrayKeys       = "fe_array_keys_$uniqid";
        $nItems          = "fe_n_items_$uniqid";
        $nItemsProcessed = "fe_n_items_processed_$uniqid";
        $i               = "fe_i_$uniqid";
        $key             = "fe_key_$uniqid";
        $val             = "fe_val_$uniqid";
        $offset          = "fe_offset_$uniqid";
        $max             = "fe_max_$uniqid";
        $reverse         = "fe_reverse_$uniqid";
        $firstVal        = "fe_first_val_$uniqid";
        $lastVal         = "fe_last_val_$uniqid";

        $variableStack   = "fe_variable_stack_$uniqid";
        $namesArray = array( $array, $arrayKeys, $nItems, $nItemsProcessed, $i, $key, $val, $offset, $max, $reverse, $firstVal, $lastVal );

        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "if ( !isset( \$$variableStack ) ) \$$variableStack = array();" );
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "\$" . $variableStack ."[] = compact( '" . implode( "', '", $namesArray ) . "' );" );

        $newNodes[] = eZTemplateNodeTool::createVariableNode( false, $parameters['array'], $nodePlacement, array( 'text-result' => false ), $array );
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "\$$arrayKeys = is_array( \$$array ) ? array_keys( \$$array ) : array();" );
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "\$$nItems = count( \$$arrayKeys );" );
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "\$$nItemsProcessed = 0;" );


        // process offset, max and reverse parameters
        if ( isset( $parameters['offset'] ) )
            $newNodes[] = eZTemplateNodeTool::createVariableNode( false, $parameters['offset'], $nodePlacement, array( 'text-result' => false ), $offset );
        else
            $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "\$$offset = 0;" );

        if ( isset( $parameters['max'] ) )
            $newNodes[] = eZTemplateNodeTool::createVariableNode( false, $parameters['max'], $nodePlacement, array( 'text-result' => false ), $max );
        else
            $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "\$$max = \$$nItems - \$$offset;" );

        if ( isset( $parameters['reverse'] ) )
            $newNodes[] = eZTemplateNodeTool::createVariableNode( false, $parameters['reverse'], $nodePlacement, array( 'text-result' => false ), $reverse );
        else
            $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "\$$reverse = false;" );


        // fix definitely incorrect offset
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "if ( \$$offset < 0 || \$$offset >= \$$nItems )\n{\n".
                                                               "    \$$offset = ( \$$offset < 0 ) ? 0 : \$$nItems;\n".
                                                               "    if ( \$$nItems || \$$offset < 0 )\n {\n".
                                                               "        eZDebug::writeWarning(\"Invalid 'offset' parameter specified: '\$$offset'. Array count: \$$nItems\");   \n}\n}" );
        // fix definitely incorrect max
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "if ( \$$max < 0 || \$$offset + \$$max > \$$nItems )\n{\n".
                                                               "    if ( \$$max < 0 )\n eZDebug::writeWarning(\"Invalid 'max' parameter specified: \$$max\");\n".
                                                               "    \$$max = \$$nItems - \$$offset;\n}" );

        // initialize first and last indexes to iterate between them
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "if ( \$$reverse )\n" .
                                                               "{\n" .
                                                               "    \$$firstVal = \$$nItems - 1 - \$$offset;\n" .
                                                               "    \$$lastVal  = 0;\n" .
                                                               "}\n" .
                                                               "else\n" .
                                                               "{\n" .
                                                               "    \$$firstVal = \$$offset;\n" .
                                                               "    \$$lastVal  = \$$nItems - 1;\n" .
                                                               "}" );

        // generate loop header
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "// foreach" );
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "for ( \$$i = \$$firstVal; " .
                                                               "\$$nItemsProcessed < \$$max && ( \$$reverse ? \$$i >= \$$lastVal : \$$i <= \$$lastVal ); " .
                                                               "\$$reverse ? \$$i-- : \$$i++ )\n" .
                                                               "{" );
        $newNodes[] = eZTemplateNodeTool::createSpacingIncreaseNode();

        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "\$$key = \$${arrayKeys}[\$$i];" );
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "\$$val = \$${array}[\$$key];" );

        // export $itemVar
        $newNodes[] = eZTemplateNodeTool::createVariableNode( false, "$val", $nodePlacement, array(),
                                                              $parameters['item_var'][0][1],
                                                              false, true, true );

        // export $keyVar (if specified)
        if ( isset( $parameters['key_var'] ) )
        {
            $newNodes[] = eZTemplateNodeTool::createVariableNode( false, "$key", $nodePlacement, array(),
                                                                  $parameters['key_var'][0][1],
                                                                  false, true, true );
        }

        $loop->processBody();

        // generate loop footer
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "\$$nItemsProcessed++;" );
        $newNodes[] = eZTemplateNodeTool::createSpacingDecreaseNode();
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "} // foreach" );

        $loop->cleanup();

        // unset the loop variables
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "if ( count( \$$variableStack ) ) extract( array_pop( \$$variableStack ) );\n" );
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "else\n{\n" );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $array );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $arrayKeys );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $nItems );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $nItemsProcessed );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $i );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $key );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $val );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $offset );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $max );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $reverse );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $firstVal );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $lastVal );

        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( $variableStack );
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "}\n" );

        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "// foreach ends" );

        return $newNodes;
    }
465221
def parse_tag(template, l_del, r_del):
    """"""
    global _CURRENT_LINE
    global _LAST_TAG_LINE

    tag_types = {
        '!': 'comment',
        '#': 'section',
        '^': 'inverted section',
        '/': 'end',
        '>': 'partial',
        '=': 'set delimiter?',
        '{': 'no escape?',
        '&': 'no escape'
    }

    # Get the tag
    try:
        tag, template = template.split(r_del, 1)
    except ValueError:
        raise ChevronError('unclosed tag '
                           'at line {0}'.format(_CURRENT_LINE))

    # Find the type meaning of the first character
    tag_type = tag_types.get(tag[0], 'variable')

    # If the type is not a variable
    if tag_type != 'variable':
        # Then that first character is not needed
        tag = tag[1:]

    # If we might be a set delimiter tag
    if tag_type == 'set delimiter?':
        # Double check to make sure we are
        if tag.endswith('='):
            tag_type = 'set delimiter'
            # Remove the equal sign
            tag = tag[:-1]

        # Otherwise we should complain
        else:
            raise ChevronError('unclosed set delimiter tag\n'
                               'at line {0}'.format(_CURRENT_LINE))

    # If we might be a no html escape tag
    elif tag_type == 'no escape?':
        # And we have a third curly brace
        # (And are using curly braces as delimiters)
        if l_del == '{{' and r_del == '}}' and template.startswith('}'):
            # Then we are a no html escape tag
            template = template[1:]
            tag_type = 'no escape'

    # Strip the whitespace off the key and return
    return ((tag_type, tag.strip()), template)
125438
def _compile_template_re(delimiters):
    
    # The possible tag type characters following the opening tag,
    # excluding "=" and "{".
    tag_types = "!>&/#^"

    # TODO: are we following this in the spec?
    #
    #   The tag's content MUST be a non-whitespace character sequence
    #   NOT containing the current closing delimiter.
    #
    tag = r"""
        (?P<whitespace>[\ \t]*)
        %(otag)s \s*
        (?:
          (?P<change>=) \s* (?P<delims>.+?)   \s* = |
          (?P<raw>{)    \s* (?P<raw_name>.+?) \s* } |
          (?P<tag>[%(tag_types)s]?)  \s* (?P<tag_key>[\s\S]+?)
        )
        \s* %(ctag)s
    """ % {'tag_types': tag_types, 'otag': re.escape(delimiters[0]), 'ctag': re.escape(delimiters[1])}

    return re.compile(tag, re.VERBOSE)