生成文件

@param ve 模板引擎
@param templateFileName 模板文件名
@param context 上下文
@param destPath 目标路径（绝对）
175499
public static void toFile(VelocityEngine ve, String templateFileName, VelocityContext context, String destPath) {
		toFile(ve.getTemplate(templateFileName), context, destPath);
	}
435601
function buildVdt(destPath) {
    return gulp.src(['./components/**/*.vdt'], {base: './'})
        .pipe(vdt({
            format: 'cjs',
            delimiters: ['{{', '}}'],
            noWith: true,
            skipWhitespace: true,
        }))
        .pipe(babel())
        .pipe(tap(function(file) {
            file.path = file.path.replace('.js', '.vdt.js');
        }))
        .pipe(gulp.dest(destPath));
}
686926
function createTemplateEngine(output, currentFile) {
    var book = output.getBook();
    var state = output.getState();
    var i18n = state.getI18n();
    var config = book.getConfig();
    var summary = book.getSummary();
    var outputFolder = output.getRoot();

    // Search paths for templates
    var searchPaths = listSearchPaths(output);
    var tplSearchPaths = searchPaths.map(templateFolder);

    // Create loader
    var loader = new Templating.ThemesLoader(tplSearchPaths);

    // Get languages
    var language = config.getValue('language');

    // Create API context
    var context = Api.encodeGlobal(output);


    /**
     * Check if a file exists
     * @param {String} fileName
     * @return {Boolean}
     */
    function fileExists(fileName) {
        if (!fileName) {
            return false;
        }

        var filePath = PathUtils.resolveInRoot(outputFolder, fileName);
        return fs.existsSync(filePath);
    }

    /**
     * Return an article by its path
     * @param {String} filePath
     * @return {Object|undefined}
     */
    function getArticleByPath(filePath) {
        var article = summary.getByPath(filePath);
        if (!article) return undefined;

        return JSONUtils.encodeSummaryArticle(article);
    }

    /**
     * Return a page by its path
     * @param {String} filePath
     * @return {Object|undefined}
     */
    function getPageByPath(filePath) {
        var page = output.getPage(filePath);
        if (!page) return undefined;

        return JSONUtils.encodePage(page, summary);
    }

    return TemplateEngine.create({
        loader: loader,

        context: context,

        globals: {
            getArticleByPath: getArticleByPath,
            getPageByPath: getPageByPath,
            fileExists: fileExists
        },

        filters: defaultFilters.merge({
            /**
             * Translate a sentence
             */
            t: function t(s) {
                return i18n.t(language, s);
            },

            /**
             * Resolve an absolute file path into a
             * relative path.
             * it also resolve pages
             */
            resolveFile: function(filePath) {
                filePath = resolveFileToURL(output, filePath);
                return LocationUtils.relativeForFile(currentFile, filePath);
            },

            resolveAsset: function(filePath) {
                filePath = LocationUtils.toAbsolute(filePath, '', '');
                filePath = path.join('gitbook', filePath);
                filePath = LocationUtils.relativeForFile(currentFile, filePath);

                // Use assets from parent if language book
                if (book.isLanguageBook()) {
                    filePath = path.join('../', filePath);
                }

                return LocationUtils.normalize(filePath);
            },


            fileExists: deprecate.method(book, 'fileExists', fileExists, 'Filter "fileExists" is deprecated, use "fileExists(filename)" '),
            getArticleByPath: deprecate.method(book, 'getArticleByPath', fileExists, 'Filter "getArticleByPath" is deprecated, use "getArticleByPath(filename)" '),

            contentURL: function(filePath) {
                return fileToURL(output, filePath);
            }
        }),

        extensions: {
            'DoExtension': new DoExtension()
        }
    });
}
1023337
function View_renderFile(templateName, locals, viewsPath) {
            if (!viewsPath) {
                viewsPath = di.getAlias('viewsPath');
            }
            return this.swig.renderFile(viewsPath + templateName, locals);
        }
1355591
protected File generateTemplate(File template, Instance instance) throws IOException {

		String scriptName = instance.getName().replace( "\\s+", "_" );
		File generated = File.createTempFile( scriptName, ".script");
		InstanceTemplateHelper.injectInstanceImports(instance, template, generated);

		return generated;
	}
1248590
def data_context_name(fn):
    
    return os.path.join(os.path.dirname(__file__), "template_data", fn)
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));
  });
}
205988
def merge_files(context):
  
  resolver = EFTemplateResolver(
      profile=context.profile,
      region=context.region,
      env=context.env,
      service=context.service
  )

  try:
    with open(context.template_path, 'r') as f:
      template_body = f.read()
      f.close()
  except IOError as error:
    raise IOError("Error loading template file: {} {}".format(context.template_path, repr(error)))

  if context.no_params is False:
    try:
      with open(context.param_path, 'r') as f:
        param_body = f.read()
        f.close()
    except IOError as error:
      raise IOError("Error loading param file: {} {}".format(context.param_path, repr(error)))

    dest = yaml.safe_load(param_body)["dest"]

    # if 'dest' for the current object contains an 'environments' list, check it
    if "environments" in dest:
      if not resolver.resolved["ENV_SHORT"] in dest["environments"]:
        print("Environment: {} not enabled for {}".format(resolver.resolved["ENV_SHORT"], context.template_path))
        return

    # Process the template_body - apply context + parameters
    resolver.load(template_body, param_body)
  else:
    resolver.load(template_body)
  rendered_body = resolver.render()

  if not resolver.resolved_ok():
    raise RuntimeError("Couldn't resolve all symbols; template has leftover {{ or }}: {}".format(resolver.unresolved_symbols()))

  if context.lint:
    if context.template_path.endswith(".json"):
      try:
        json.loads(rendered_body, strict=False)
        print("JSON passed linting process.")
      except ValueError as e:
        fail("JSON failed linting process.", e)
    elif context.template_path.endswith((".yml", ".yaml")):
      conf = yamllint_config.YamlLintConfig(content='extends: relaxed')
      lint_output = yamllinter.run(rendered_body, conf)
      lint_level = 'error'
      lint_errors = [issue for issue in lint_output if issue.level == lint_level]
      if lint_errors:
        split_body = rendered_body.splitlines()
        for error in lint_errors:
          print(error)
          # printing line - 1 because lists start at 0, but files at 1
          print("\t", split_body[error.line - 1])
        fail("YAML failed linting process.")

  if context.verbose:
    print(context)
    if context.no_params:
      print('no_params flag set to true!')
      print('Inline template resolution based on external symbol lookup only and no destination for file write.\n')
    else:
      dir_path = normpath(dirname(dest["path"]))
      print("make directories: {} {}".format(dir_path, dest["dir_perm"]))
      print("chmod file to: " + dest["file_perm"])
      user, group = dest["user_group"].split(":")
      print("chown last directory in path to user: {}, group: {}".format(user, group))
      print("chown file to user: {}, group: {}\n".format(user, group))

    print("template body:\n{}\nrendered body:\n{}\n".format(template_body, rendered_body))
  elif context.silent:
    print("Config template rendered successfully.")
  else:
    print(rendered_body)
283342
def render(self, template, filename, context={}, filters={}):
        
        filename = os.path.normpath(filename)
        path, file = os.path.split(filename)
        try:
            os.makedirs(path)
        except OSError as exception:
            if exception.errno != errno.EEXIST:
                raise

        path, file = os.path.split(template)
        loader = jinja2.FileSystemLoader(path)
        env = jinja2.Environment(loader=loader, trim_blocks=True, lstrip_blocks=True)
        env.filters.update(filters)
        template = env.get_template(file)
        text = template.render(context)
        with open(filename, 'wt') as f:
            f.write(text)
520
public static void toFile(Template template, VelocityContext context, String destPath) {
		PrintWriter writer = null;
		try {
			writer = FileUtil.getPrintWriter(destPath, Velocity.getProperty(Velocity.INPUT_ENCODING).toString(), false);
			merge(template, context, writer);
		} catch (IORuntimeException e) {
			throw new UtilException(e, "Write Velocity content to [{}] error!", destPath);
		} finally {
			IoUtil.close(writer);
		}
	}
1306604
function(handlebars, directory, filepath, opts, done) {
		var regex = (typeof opts.match === 'string') ? new RegExp(opts.match) : opts.match || /\.(html|hbs)$/,
			isValidTemplate = regex.test(filepath);

		if (!isValidTemplate) {
			return done(null);
		}

		fs.readFile(filepath, 'utf8', function(err, data) {
			if (!err) {
				var ext = path.extname(filepath);
				var templateName = path.relative(directory, filepath)
				.slice(0, -(ext.length)).replace(/[ -]/g, '_').replace(/\\/g, '/');
				if (typeof opts.name === 'function') templateName = opts.name(templateName);
				handlebars.registerPartial(templateName, data);
				return done(undefined, templateName);
			}

			done(err);
		});
	}
812750
protected function renderTemplate($templatePathAndFilename, array $contextVariables)
    {
        $standaloneView = new StandaloneView();
        $standaloneView->setTemplatePathAndFilename($templatePathAndFilename);
        $standaloneView->assignMultiple($contextVariables);
        return $standaloneView->render();
    }
678993
def gen_file_jinja(self, template_file, data, output, dest_path):
        if not os.path.exists(dest_path):
            os.makedirs(dest_path)
        output = join(dest_path, output)
        logger.debug("Generating: %s" % output)

        
        env = Environment()
        env.loader = FileSystemLoader(self.TEMPLATE_DIR)
        # TODO: undefined=StrictUndefined - this needs fixes in templates
        template = env.get_template(template_file)
        target_text = template.render(data)

        open(output, "w").write(target_text)
        return dirname(output), output
802258
function resolveTemplate(file, pathes) {
    var filePath = file.path,
        templateContent = '';

    for(var i = 0, len = pathes.length; i < len; i ++) {
        templateContent += fs.readFileSync(pathes[i], {encoding: 'utf-8'}) + "\r\n";
    }

    return templateContent;
}
175259
def generate(template_path, dest_path, ivars)
      dest_path += '.html'
      ext_to_remove = File.extname(dest_path)
      web_path = '/' + dest_path.sub(/#{ext_to_remove}$/, '') + '/'
      compiler = Ichiban::HTMLCompiler.new(
        Ichiban::HTMLFile.new(
          File.join('html', template_path)
        )
      )
      compiler.ivars = {:_current_path => web_path}.merge(ivars)
      html = compiler.compile_to_str      
      abs_dest_path = File.join(Ichiban.project_root, 'compiled', dest_path)
      FileUtils.mkdir_p File.dirname(abs_dest_path)
      File.open(abs_dest_path, 'w') do |f|
        f << html
      end
      Ichiban.logger.compilation(
        File.join(Ichiban.project_root, 'html', template_path),
        File.join(Ichiban.project_root, 'compiled', dest_path)
      )
    end
547195
def template_path(self):
        
        return super(HideCodeHTMLExporter, self).template_path + [os.path.join(os.path.dirname(__file__), "Templates")]
1175374
function(context, args, stack) {
		var path = args[0],
			template = args[1],
			pathIsString = typeof path === 'string';
		ctx = new Context(pathIsString ? context.get(path) : path, context, pathIsString ? path : null);
		stack.push(ctx);
		firstPass(template, ctx, stack);
	}