xtemplate engine

@example
modulex.use('xtemplate', function(XTemplate){
document.writeln(new XTemplate('{{title}}').render({title:2}));
});

@class XTemplate
@extends XTemplate.Runtime
513142
function XTemplate(tpl, config) {
  var tplType = (typeof tpl);
  if (tplType !== 'string' && tplType !== 'function') {
    config = tpl;
    tpl = undefined;
  }
  config = this.config = util.merge(XTemplate.globalConfig, config);
  if (tplType === 'string') {
    try {
      tpl = this.compile(tpl, config.name);
    } catch (err) {
      this.compileError = err;
    }
  }
  XTemplateRuntime.call(this, tpl, config);
}
1057736
function(name, ctx, cb) {
                if (lib.isFunction(ctx)) {
                    cb = ctx;
                    ctx = null;
                }

                // We support a synchronous API to make it easier to migrate
                // existing code to async. This works because if you don't do
                // anything async work, the whole thing is actually run
                // synchronously.
                var syncResult = null;

                this.getTemplate(name, function(err, tmpl) {
                    if (err && cb) {
                        cb(err);
                    } else if (err) {
                        throw err;
                    } else {
                        tmpl.render(ctx, cb || function(err, res) {
                            if (err) {
                                throw err;
                            }
                            syncResult = res;
                        });
                    }
                });

                return syncResult;
            }
1301240
function buildRunTemplate(opts, callback) {
  var viewOpt = {
    directory: opts.directory,
    processCommand: opts.command,
    user: opts.user,
    processEnvDir: opts.processEnvDir
  };

  renderTemplate(templateFilePath('run', opts.templateOpt), viewOpt, function(err, renderedOutput) {
    if (err) {
      return callback(err.message);
    } else {
      return fs.writeFile(opts.processRunPath, renderedOutput, function(err) {
	if (err) {
	  return callback(err.message);
	} else {
	  fs.chmodSync(opts.processRunPath, 0755);
	  return callback(null);
	}
      });
    }
  });
}
1371846
function compileTemplates() {
  const mainHtml = fs.readFileSync(path.resolve(docsDir, 'src/template.html'), {
    encoding: 'utf8',
  });
  const mainTemplate = Handlebars.compile(mainHtml);

  function createPage(fileName, tab, content) {
    const html = mainTemplate({
      tabs: [{
        title: 'Get started',
        url: 'get-started.html',
        selected: tab === 'get-started',
      }, {
        title: 'Components',
        url: 'components.html',
        selected: tab === 'components',
      }],
      content,
      luiVersion: LUI_VERSION,
    });
    fileUtil.writeFile(path.resolve(docsDir, 'dist', fileName), html);
  }

  function createIndexPage() {
    const content = fs.readFileSync(path.resolve(docsDir, 'src/pages/index.html'), {
      encoding: 'utf8',
    });
    const template = Handlebars.compile(content);
    const html = template();
    return createPage('index.html', 'index', html);
  }

  function createGetStartedPage() {
    const content = fs.readFileSync(path.resolve(docsDir, 'src/pages/get-started.html'), {
      encoding: 'utf8',
    });
    const template = Handlebars.compile(content);
    const html = template({
      luiVersion: LUI_VERSION,
    });
    return createPage('get-started.html', 'get-started', html);
  }

  function createComponentPage(templateName, template, tab, content) {
    return createPage(templateName, tab, template({
      content,
      sections: sections.map(section => ({
        name: section.name,
        pages: section.pages.map(page => ({
          name: page.name,
          template: page.template,
          selected: page.template === templateName,
        })),
      })),
    }));
  }

  function createComponentPages() {
    const componentHtml = fs.readFileSync(path.resolve(docsDir, 'src/component-template.html'), {
      encoding: 'utf8',
    });
    const componentTemplate = Handlebars.compile(componentHtml);

    sections.forEach((section) => {
      section.pages.forEach((page) => {
        const file = `src/pages/${page.template}`;
        const fileContent = fs.readFileSync(path.resolve(docsDir, file), {
          encoding: 'utf8',
        });

        const template = Handlebars.compile(fileContent);
        const html = template();

        createComponentPage(page.template, componentTemplate, 'components', html);
      });
    });

    const file = 'src/pages/components.html';
    const fileContent = fs.readFileSync(path.resolve(docsDir, file), {
      encoding: 'utf8',
    });
    createComponentPage('components.html', componentTemplate, 'components', fileContent);
  }

  createIndexPage();
  createGetStartedPage();
  createComponentPages();
}
262268
@Override
    public ITemplate __cloneMe(RythmEngine engine, ITemplate caller) {
        if (null == engine) throw new NullPointerException();
        TemplateBase tmpl = __internalClone();
        if (tmpl.__parent != null) {
            tmpl.__parent = (TemplateBase) tmpl.__parent.__cloneMe(engine, caller);
        }
        tmpl.__engine = engine;
        //tmpl.__templateClass = __templateClass;
        tmpl.__ctx = new __Context();
        //if (null != buffer) tmpl.__buffer = buffer;
        if (null != __buffer) tmpl.__buffer = new StringBuilder();
        tmpl.__renderArgs = new HashMap<String, Object>(__renderArgs.size());
        //tmpl.layoutContent = "";
        tmpl.layoutSections = new HashMap<String, String>();
        tmpl.layoutSections0 = new HashMap<String, String>();
        tmpl.renderProperties = new HashMap<String, Object>();
        //tmpl.section = null;
        //tmpl.tmpCaller = null;
        //tmpl.tmpOut = null;
        //tmpl.__logTime = __logTime;
        //tmpl.w = null;
        //tmpl.os = null;
        if (null != caller) {
            tmpl.__caller = (TextBuilder) caller;
            Map<String, Object> callerRenderArgs = new HashMap<String, Object>(((TemplateBase) caller).__renderArgs);
            Map<String, Class> types = tmpl.__renderArgTypeMap();
            for (Map.Entry<String, Object> entry : callerRenderArgs.entrySet()) {
                if (tmpl.__renderArgs.containsKey(entry.getKey())) continue;
                Object o = entry.getValue();
                if (null == o || __isDefVal(o)) continue;
                Class<?> c = types.get(entry.getKey());

                if (null == c || c.isAssignableFrom(o.getClass())) {
                    tmpl.__setRenderArg(entry.getKey(), o);
                }
            }
        }
        tmpl.__setUserContext(engine.renderSettings.userContext());
        return tmpl;
    }
1062609
function (arrayValue, index) {
            // Support selecting template as a function of the data being rendered
            arrayItemContext = parentBindingContext['createChildContext'](arrayValue, options['as'], function(context) {
                context['$index'] = index;
            });

            var templateName = resolveTemplateName(template, arrayValue, arrayItemContext);
            return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
        }
652714
function() {
            var tpl = this.options.template;

            //first pass
            $.each(this.map, function(k, v) {
                v = v[0]; 
                var r = new RegExp(v+'+'),
                    token = v.length > 1 ? v.substring(1, 2) : v;
                    
                tpl = tpl.replace(r, '{'+token+'}');
            });

            //replace spaces with &nbsp;
            tpl = tpl.replace(/ /g, '&nbsp;');

            //second pass
            $.each(this.map, function(k, v) {
                v = v[0];
                var token = v.length > 1 ? v.substring(1, 2) : v;
                    
                tpl = tpl.replace('{'+token+'}', '<select class="'+k+'"></select>');
            });   

            return tpl;
        }
628932
public static String render(Template template, Map<String, Object> bindingMap) {
		template.binding(bindingMap);
		return template.render();
	}
1304007
@Override
	public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
		WSection section = (WSection) component;
		XmlStringBuilder xml = renderContext.getWriter();

		boolean renderChildren = isRenderContent(section);

		xml.appendTagOpen("ui:section");
		xml.appendAttribute("id", component.getId());
		xml.appendOptionalAttribute("class", component.getHtmlClass());
		xml.appendOptionalAttribute("track", component.isTracking(), "true");
		if (SectionMode.LAZY.equals(section.getMode())) {
			xml.appendOptionalAttribute("hidden", !renderChildren, "true");
		} else {
			xml.appendOptionalAttribute("hidden", component.isHidden(), "true");
		}

		SectionMode mode = section.getMode();
		if (mode != null) {
			switch (mode) {
				case LAZY:
					xml.appendAttribute("mode", "lazy");
					break;
				case EAGER:
					xml.appendAttribute("mode", "eager");
					break;
				default:
					throw new SystemException("Unknown section mode: " + section.getMode());
			}
		}

		xml.appendClose();

		// Render margin
		MarginRendererUtil.renderMargin(section, renderContext);

		if (renderChildren) {
			// Label
			section.getDecoratedLabel().paint(renderContext);
			// Content
			section.getContent().paint(renderContext);
		}

		xml.appendEndTag("ui:section");
	}
1142047
function render(engine, str, locals, engineOptions) {
  try {
    var output = engine.render(engine.engine, str, locals, engineOptions)
  } catch(e) {
    throw new Error(
      NAME + ': there was a problem rendering the template:\n' + e)
  }
  return output
}
398271
function renderTemplate(engine, filePath, content, context) {
    context = context || {};

    // Mutable objects to contains all blocks requiring post-processing
    var blocks = {};

    // Create nunjucks environment
    var env = engine.toNunjucks(blocks);

    // Replace shortcuts from plugin's blocks
    content = replaceShortcuts(engine.getBlocks(), filePath, content);

    return timing.measure(
        'template.render',

        Promise.nfcall(
            env.renderString.bind(env),
            content,
            context,
            {
                path: filePath
            }
        )
        .then(function(content) {
            return TemplateOutput.create(content, blocks);
        })
    );
}
860730
function template(
  { template, types: t },
  opts,
  { imports, componentName, props, jsx, exports },
) {
  const name = componentName.name.replace('Svg', '');

  jsx
    .openingElement
    .attributes = [
      t.jsxAttribute(
        t.jsxIdentifier('aria-label'),
        t.stringLiteral(`icon_${name}`)
      ),
      ...jsx.openingElement.attributes
    ];

  const titleElement = t.jsxElement(
    t.jsxOpeningElement(t.jsxIdentifier('title'), []),
    t.jsxClosingElement(t.jsxIdentifier('title')),
    [t.jsxText(`${name}`)],
  )

  jsx.children = [titleElement, ...jsx.children];

  return template.ast`
    ${imports}
    import withIcon from './withIcon';
    const ${name} = (${props}) => ${jsx}
    export default withIcon(${name});
  `
}
1650
function createDomElementFromTemplate(html) {
    //match container markers like <@element/>
    let containerTags = html.match(rContainerGlobal) || [];

    for (let containerTag of containerTags) {
        let [, containerName, attrs = ''] = rContainer.exec(containerTag);
        let template = `<script type="x" ${ATTR}="${containerName}">${attrs.trim()}</script>`;

        html = html.split(containerTag).join(template);
    }

    //match attribute markers like <span @element></span>
    let allTags = html.match(rTags) || [];

    for (let tag of allTags) {
        let result = rAttr.exec(tag);

        if (result) {
            let elName = result[1];
            html = html.split(tag).join(tag.replace(`@${elName}`, `${ATTR}="${elName}"`));
        }
    }

    return $.create(html.trim());
}
1289052
function renderTemplateLoader(source) {
  // Get the loader options object.
  var options = getOptions(this)
  // Get the template locals.
  var locals = getLocals.call(this, options)
  // Create info object of the filename of the resource being loaded.
  var info = { filename: this.resourcePath }
  // Get the engine options to be passed to the engine.
  var engineOptions = getEngineOptions.call(this, options.engineOptions, info)
  // Get the template renderer
  var renderer = getRenderer.call(this, options.engine)
  // Call options.init.
  init.call(this, renderer.engine, info, options)
  // Render the template
  var result = render(renderer, source, locals, engineOptions)
  // Assign the tempate to module.exports.
  return 'module.exports = ' + JSON.stringify(result)
}
63931
function compileTemplate(name) {
        // Directive compile function
        return function (tElement, tAttrs, transclude) {
            var rootElement = document.createElement("div");
            Object.keys(tAttrs).forEach(function (key) {
                if (key[0] !== '$') {
                    rootElement.setAttribute(key, tAttrs[key]);
                }
            });
            var immediateToken;
            // Directive link function
            return function ($scope, elements, attrs, parents) {
                var parent = parents.reduce(function (found, item) { return found || item; });
                parent[name] = function (itemPromise) {
                    // Actual item renderer
                    return WinJS.Promise.as(itemPromise).then(function (item) {
                        var itemScope = $scope.$new();
                        itemScope.item = item;
                        var result = rootElement.cloneNode(false);
                        transclude(itemScope, function (clonedElement) {
                            for (var i = 0, len = clonedElement.length; i < len; i++) {
                                result.appendChild(clonedElement[i]);
                            }
                        });
                        WinJS.Utilities.markDisposable(result, function () {
                            itemScope.$destroy();
                        });
                        immediateToken = immediateToken || setImmediate(function () {
                            immediateToken = null;
                            itemScope.$apply();
                        });
                        return result;
                    })
                };
            };
        };
    }
4859
function compile(tmpl, conf) {
  const c = Object.assign(
    {},
    settings,
    conf,
  );

  const template = new LayoutTemplate({
    conf: c,
    tmpl,
  });

  return bracket.compile(
    template.compile(),
    template.conf,
  );
}
154735
def render(xm=Builder::XmlMarkup.new(:indent => 2))
      [:name, :visibility, :address].each do |a|
        xm.__send__(a, self.__send__(a)) unless self.__send__(a).nil?
      end
      
      xm.description { xm.cdata!(description) } unless description.nil?
      xm.open(self.open) unless open.nil?
      
      xm.phoneNumber(phone_number) unless phone_number.nil?
      xm.styleUrl(style_url) unless style_url.nil?
      
      unless address_details.nil?
        xm.AddressDetails(:xmlns => "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0") { address_details.render(xm) } 
      end
      
      xm.Snippet(snippet.text, snippet.max_lines) unless snippet.nil?
      
      xm.LookAt { look_at.render(xm) } unless look_at.nil?
      xm.TimePrimitive { time_primitive.render(xm) } unless time_primitive.nil?
      xm.StyleSelector { style_selector.render(xm) } unless style_selector.nil?
    end