generate the template for a loop node
171339
function loopgen(dom, sel, loop, fns){
    var already = false, ls, sorter, filter, prop;
    for(prop in loop){
      if(loop.hasOwnProperty(prop)){
        if(prop === 'sort'){
          sorter = loop.sort;
          continue;
        }else if(prop === 'filter'){
          filter = loop.filter;
          continue;
        }
        if(already){
          error('cannot have more than one loop on a target');
        }
        ls = prop;
        already = true;
      }
    }
    if(!ls){
      error('Error in the selector: ' + sel + '\nA directive action must be a string, a function or a loop(<-)');
    }
    var dsel = loop[ls];
    // if it's a simple data selector then we default to contents, not replacement.
    if(typeof(dsel) === 'string' || typeof(dsel) === 'function'){
      loop = {};
      loop[ls] = {root: dsel};
      return loopgen(dom, sel, loop, fns);
    }
    var spec = parseloopspec(ls),
      itersel = dataselectfn(spec.sel),
      target = gettarget(dom, sel, true),
      nodes = target.nodes;

    for(i = 0; i < nodes.length; i++){
      var node = nodes[i],
        inner = compiler(node, dsel);
      fns[fns.length] = wrapquote(target.quotefn, loopfn(spec.name, itersel, inner, sorter, filter));
      target.nodes = [node];    // N.B. side effect on target.
      setsig(target, fns.length - 1);
    }
  }
1103283
def prepare(self, context):
        
        self.params = {}

        # no params, not even a newline
        if not self.nodelist:
            return

        # just static text, no vars, assume one TextNode
        if not self.nodelist.contains_nontext:
            text = self.nodelist[0].s.strip()

        # vars in params, we have to render
        else:
            context.push()
            context['object'] = self.obj
            text = self.nodelist.render(context)
            context.pop()

        if text:
            self.params = self.resolve_params(text)

        # override the default template from the parameters
        if 'template_name' in self.params:
            self.template_name = self.params['template_name']
86706
private void prepTemplatePlaceholders(Node fn) {
    final List<String> locals = templateLocals;
    final List<String> params = templateParams;
    final Map<String, JSType> paramTypes = new HashMap<>();

    // drop the function name so it isn't include in the name maps
    String fnName = fn.getFirstChild().getString();
    fn.getFirstChild().setString("");

    // Build a list of parameter names and types.
    Node templateParametersNode = fn.getSecondChild();
    JSDocInfo info = NodeUtil.getBestJSDocInfo(fn);
    if (templateParametersNode.hasChildren()) {
      Preconditions.checkNotNull(info,
          "Missing JSDoc declaration for template function %s", fnName);
    }
    for (Node paramNode : templateParametersNode.children()) {
      String name = paramNode.getString();
      JSTypeExpression expression = info.getParameterType(name);
      Preconditions.checkNotNull(expression,
          "Missing JSDoc for parameter %s of template function %s",
          name, fnName);
      JSType type = typeRegistry.evaluateTypeExpressionInGlobalScope(expression);
      checkNotNull(type);
      params.add(name);
      paramTypes.put(name, type);
    }

    // Find references to string literals, local variables and parameters and replace them.
    traverse(
        fn,
        new Visitor() {
          @Override
          public void visit(Node n) {
            if (n.isName()) {
              Node parent = n.getParent();
              String name = n.getString();
              if (!name.isEmpty() && parent.isVar() && !locals.contains(name)) {
                locals.add(n.getString());
              }

              if (params.contains(name)) {
                JSType type = paramTypes.get(name);
                boolean isStringLiteral =
                    type.isStringValueType() && name.startsWith("string_literal");
                replaceNodeInPlace(
                    n, createTemplateParameterNode(params.indexOf(name), type, isStringLiteral));
              } else if (locals.contains(name)) {
                replaceNodeInPlace(n, createTemplateLocalNameNode(locals.indexOf(name)));
              }
            }
          }
        });
  }
1141229
function generateTemplate(context) {
  let _page;
  let _phantom;
  phantom.create([], { logLevel: 'error' }).then(function (ph) {
    _phantom = ph;
    ph.createPage()
      .then(page => {
        _page = page;
        const url = path.join(context.config.destRoot, context.sample.embed);
        return _page.property('viewportSize', {width: 1024, height: 768})
          .then(() => _page.open(url) );
      })
      .then(status => {
        return _page.evaluate(function() {
          const element = document.querySelector('#source-panel');
          const height = element.getBoundingClientRect().top + element.offsetHeight;
          return height;
        });
      })
      .then(height => {
        context.sample.height = height;
        generate(context.sample.template, templates.template, context);
      })
      .then(() => {
        _page.close();
        _phantom.exit();
      })
      .catch(err => console.log(err));
  });
}
163451
def linkify_templates(self):
        
        # First we create a list of all templates
        for i in itertools.chain(iter(list(self.items.values())),
                                 iter(list(self.templates.values()))):
            self.linkify_item_templates(i)
        for i in self:
            i.tags = self.get_all_tags(i)
1117946
def _build_new_template(self, stack, parameters):
        
        log_lines = ["New template parameters:"]
        for param in sorted(parameters,
                            key=lambda param: param['ParameterKey']):
            log_lines.append("%s = %s" % (param['ParameterKey'],
                                          param['ParameterValue']))

        log_lines.append("\nNew template contents:")
        log_lines.append("".join(stack))
        return log_lines
1287212
def generate_template_arc_tree(self):
        '''
        
        '''
        arc_root = self.arc_root_node
        if not arc_root:
            arc_root = ArcElementNode.add_root(
                arc_element_type='root',
                description='root of arc %s' % self.name,
                arc=self
            )
        if arc_root.get_children():
            raise ArcIntegrityError(_("This arc already has elements. You cannot build a template on top of it"))
        for key, value in ARC_NODE_ELEMENT_DEFINITIONS.items():
            if value['milestone']:
                arc_root.add_child(arc_element_type=key, description=value['template_description'])
                arc_root.refresh_from_db()
        return ArcElementNode.objects.get(pk=arc_root.pk).get_children().count()
515026
def template(self):
        '''
        
        '''
        instance = self.template_instance()
        offset = self._chunk.offset() + instance.template_offset()
        node = TemplateNode(self._buf, offset, self._chunk, instance)
        return node
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;
    }
43077
function templateNodeTransformation( $functionName, &$node,
                                         $tpl, &$parameters, $privateData )
    {
        $undef = ( $functionName == 'undef' );
        $newNodes = array();

        if ( !$parameters )
        {
            if ( !$undef )
                // prevent execution of the function in processed mode
                return array( eZTemplateNodeTool::createCodePieceNode( "// an error occured in $functionName" ) );

            // {undef} called w/o arguments => destroy all local variables
            $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "// undef all" );
            $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "\$tpl->unsetLocalVariables();" );
            return $newNodes;
        }

        $nodePlacement = eZTemplateNodeTool::extractFunctionNodePlacement( $node );
        foreach ( array_keys( $parameters ) as $parameterName )
        {
            $parameterData = $parameters[$parameterName];
            if ( $undef )
            {
                $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "// undef \$$parameterName" );
                // generates "$tpl->unsetLocalVariable();"
                $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( array( $namespaceValue = false,
                                                                                  $scope = eZTemplate::NAMESPACE_SCOPE_LOCAL,
                                                                                  $parameterName ),
                                                                           array( 'remember_set' => false, 'local-variable' => true ) );
            }
            else
            {
                $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "// def \$$parameterName" );
                // generates "$tpl->setLocalVariable();"
                $newNodes[] = eZTemplateNodeTool::createVariableNode( false, $parameterData, $nodePlacement, array( 'local-variable' => true ),
                                                                      array( $namespaceValue = false, $scope = eZTemplate::NAMESPACE_SCOPE_LOCAL, $parameterName ),
                                                                      $onlyExisting = false, $overwrite = true, false, $rememberSet = false );
            }
        }

        return $newNodes;
    }
31308
def render_node(_node_id, value=None, noderequest={}, **kw):
    ""
    if value == None:
        kw.update( noderequest )
        results = _query(_node_id, **kw)
        current_app.logger.debug("results: %s", results)
        if results:
            values = []
            for (result, cols) in results:
                if set(cols) == set(['node_id', 'name', 'value']):
                    for subresult in result:
                        #if subresult.get('name') == kw.get('name'):
                            # This is a link node
                        current_app.logger.debug("sub: %s", subresult)
                        name = subresult['name']
                        if noderequest.get('_no_template'):
                            # For debugging or just simply viewing with the
                            # operate script we append the node_id to the name
                            # of each. This doesn't work with templates.
                            name = "{0} ({1})".format(name, subresult['node_id'])
                        values.append( {name: render_node( subresult['node_id'], noderequest=noderequest, **subresult )} )
                #elif 'node_id' and 'name' in cols:
                #    for subresult in result:
                #        current_app.logger.debug("sub2: %s", subresult)
                #        values.append( {subresult.get('name'): render_node( subresult.get('node_id'), **subresult )} )
                else:
                    values.append( result )

            value = values

    value = _short_circuit(value)
    if not noderequest.get('_no_template'):
        value = _template(_node_id, value)

    return value
891260
static function generateNodeView( $tpl, $node, $object, $languageCode, $viewMode, $offset,
                                      $cacheDir, $cachePath, $viewCacheEnabled,
                                      $viewParameters = array( 'offset' => 0, 'year' => false, 'month' => false, 'day' => false ),
                                      $collectionAttributes = false, $validation = false )
    {
        $cacheFile = eZClusterFileHandler::instance( $cachePath );
        $args = compact( "tpl", "node", "object", "languageCode", "viewMode", "offset",
                         "viewCacheEnabled",
                         "viewParameters",
                         "collectionAttributes", "validation" );
        $Result = $cacheFile->processCache( null, // no retrieve, only generate is called
                                            array( 'eZNodeviewfunctions', 'generateCallback' ),
                                            null,
                                            null,
                                            $args );
        return $Result;
    }
148659
def generate_hiera_template
      ssh_key = Bebox::Project.public_ssh_key_from_file(self.project_root, self.name)
      project_name = Bebox::Project.shortname_from_file(self.project_root)
      Bebox::PROVISION_STEPS.each do |step|
        step_dir = Bebox::Provision.step_name(step)
        generate_file_from_template("#{templates_path}/puppet/#{step}/hiera/data/environment.yaml.erb", "#{self.project_root}/puppet/steps/#{step_dir}/hiera/data/#{self.name}.yaml", {step_dir: step_dir, ssh_key: ssh_key, project_name: project_name})
      end
    end
1048790
protected function generateTemplate()
    {
        $st_annotations = $this->extractAnnotations();

        $template = array();
        $counter = 0;
        $section = null;
        $partial_template = $this->loadPartialTemplate('main');

        foreach ($st_annotations as $class => $methods) {
            foreach ($methods as $name => $docs) {
                if (isset($docs['ApiDescription'][0]['section'])) {
                  $section = $docs['ApiDescription'][0]['section'];
                }elseif(isset($docs['ApiSector'][0]['name'])){
                    $section = $docs['ApiSector'][0]['name'];
                }else{
                    $section = $class;
                }
                if (0 === count($docs)) {
                    continue;
                }

                $sampleOutput = $this->generateSampleOutput($docs, $counter);

                $tr = array(
                    '{{ elt_id }}'                  => $counter,
                    '{{ method }}'                  => $this->generateBadgeForMethod($docs),
                    '{{ route }}'                   => $docs['ApiRoute'][0]['name'],
                    '{{ description }}'             => $docs['ApiDescription'][0]['description'],
                    '{{ headers }}'                 => $this->generateHeadersTemplate($counter, $docs),
                    '{{ parameters }}'              => $this->generateParamsTemplate($counter, $docs),
                    '{{ body }}'                    => $this->generateBodyTemplate($counter, $docs),
                    '{{ sandbox_form }}'            => $this->generateSandboxForm($docs, $counter),
                    '{{ sample_response_headers }}' => $sampleOutput[0],
                    '{{ sample_response_body }}'    => $sampleOutput[1]
                );

                $template[$section][] = strtr($partial_template, $tr);
                $counter++;
            }
        }

        $output = '';

        foreach ($template as $key => $value) {
          array_unshift($value, '<h2>' . $key . '</h2>');
          $output .= implode(PHP_EOL, $value);
        }

        $this->saveTemplate($output, $this->_output_file);

        return true;
    }
589876
def generate_make_string(out_f, max_step):
    """"""
    steps = [2 ** n for n in xrange(int(math.log(max_step, 2)), -1, -1)]

    with Namespace(
        out_f,
        ['boost', 'metaparse', 'v{0}'.format(VERSION), 'impl']
    ) as nsp:
        generate_take(out_f, steps, nsp.prefix())

        out_f.write(
            '{0}template <int LenNow, int LenRemaining, char... Cs>\n'
            '{0}struct make_string;\n'
            '\n'
            '{0}template <char... Cs>'
            ' struct make_string<0, 0, Cs...> : string<> {{}};\n'
            .format(nsp.prefix())
        )

        disable_sun = False
        for i in reversed(steps):
            if i > 64 and not disable_sun:
                out_f.write('#ifndef __SUNPRO_CC\n')
                disable_sun = True
            out_f.write(
                '{0}template <int LenRemaining,{1}char... Cs>'
                ' struct make_string<{2},LenRemaining,{3}Cs...> :'
                ' concat<string<{4}>,'
                ' typename make_string<take(LenRemaining),'
                'LenRemaining-take(LenRemaining),Cs...>::type> {{}};\n'
                .format(
                    nsp.prefix(),
                    ''.join('char {0},'.format(n) for n in unique_names(i)),
                    i,
                    ''.join('{0},'.format(n) for n in unique_names(i)),
                    ','.join(unique_names(i))
                )
            )
        if disable_sun:
            out_f.write('#endif\n')
399586
function renderTemplate(template, context) {
    var esc = $(document.createElement('div'));

    function handle(ph, escape) {
      var cur = context;
      $.each(ph.split('.'), function() {
        cur = cur[this];
      });
      return escape ? esc.text(cur || "").html() : cur;
    }

    return template.replace(/<([%#])([\w\.]*)\1>/g, function() {
      return handle(arguments[2], arguments[1] == '%' ? true : false);
    });
  }
1001422
private Node transformNode(
      Node templateNode,
      Map<String, Node> templateNodeToMatchMap,
      Map<String, String> shortNames) {
    Node clone = templateNode.cloneNode();
    if (templateNode.isName()) {
      String name = templateNode.getString();
      if (templateNodeToMatchMap.containsKey(name)) {
        Node templateMatch = templateNodeToMatchMap.get(name);
        Preconditions.checkNotNull(templateMatch, "Match for %s is null", name);
        if (templateNode.getParent().isVar()) {
          // Var declarations should only copy the variable name from the saved match, but the rest
          // of the subtree should come from the template node.
          clone.setString(templateMatch.getString());
        } else {
          return templateMatch.cloneTree();
        }
      }
    } else if (templateNode.isCall()
        && templateNode.getBooleanProp(Node.FREE_CALL)
        && templateNode.getFirstChild().isName()) {
      String name = templateNode.getFirstChild().getString();
      if (templateNodeToMatchMap.containsKey(name)) {
        // If this function call matches a template parameter, don't treat it as a free call.
        // This mirrors the behavior in the TemplateAstMatcher as well as ensures the code
        // generator doesn't generate code like "(0,fn)()".
        clone.putBooleanProp(Node.FREE_CALL, false);
      }
    }
    if (templateNode.isQualifiedName()) {
      String name = templateNode.getQualifiedName();
      if (shortNames.containsKey(name)) {
        String shortName = shortNames.get(name);
        if (!shortName.equals(name)) {
          return IR.name(shortNames.get(name));
        }
      }
    }
    for (Node child : templateNode.children()) {
      clone.addChildToBack(transformNode(child, templateNodeToMatchMap, shortNames));
    }
    return clone;
  }