生成文件

@param template 模板
@param context 模板上下文
@param destPath 目标路径（绝对）
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);
		}
	}
1001577
function readTemplate(path) {
  var template = fs.readFileSync(__dirname + '/templates/' + path, 'utf8');
  for (var index in data) {
    template = template.split('__' + index + '__').join(data[index]);
  }
  return template;
}
264266
private void generate(TemplateFile input, List<OutputFile> outputs, TemplateOptions templateOptions) throws IOException {
    final String targetFileName = targetFileName(templatesPath.relativize(input.path).toString(), templateOptions);
    final OutputFile output = new OutputFile(outputPath.resolve(targetFileName).toAbsolutePath().normalize());

    if (incremental &&
        Files.exists(output.path) &&
        Files.getLastModifiedTime(output.path).toMillis() >= Files.getLastModifiedTime(input.path).toMillis()) {
      // No need to re-render but mark as generated.
      output.upToDate = true;
      outputs.add(output);
      return;
    }

    String template = new String(Files.readAllBytes(input.path), StandardCharsets.UTF_8);

    timeVelocity.start();
    template = filterVelocity(input, template, templateOptions);
    timeVelocity.stop();

    // Check if template requested ignoring a given type combination.
    if (templateOptions.isIgnored()) {
      return;
    }

    getLog().debug("Processing: " + input.getFileName() + " => " + output.path);
    try {
      timeIntrinsics.start();
      template = filterIntrinsics(template, templateOptions);
      timeIntrinsics.stop();
  
      timeComments.start();
      template = filterComments(template);
      timeComments.stop();
  
      timeTypeClassRefs.start();
      template = filterTypeClassRefs(template, templateOptions);
      template = filterStaticTokens(template, templateOptions);
      timeTypeClassRefs.stop();
    } catch (RuntimeException e) {
      getLog().error("Error processing: " + input.getFileName() + " => " + output.path + ":\n\t" + e.getMessage());
      throw e;
    }

    Files.createDirectories(output.path.getParent());
    Files.write(output.path, template.getBytes(StandardCharsets.UTF_8));

    outputs.add(output);
  }
206713
def render_template_file(file_name, context):
    
    with open(file_name, 'r+') as f:
        template = Template(f.read())
        output = template.render(context)
        f.seek(0)
        f.write(output)
        f.truncate()
817521
public static Template getClassPathTemplate(String path, String templateFileName) {
		return getTemplate(createClassPathGroupTemplate(path), templateFileName);
	}
1093156
function(context, descriptor, args, stack) {
		var path = args[0],
			template = args[1],
			ctx = stack.shift(),
			oldCtx = descriptor.context;
		descriptor.context = ctx;
		secondPass(template, ctx, descriptor, stack);
		descriptor.context = oldCtx;
	}
682585
private void buildTemplatedMetadataFile(String path) throws IOException {
    try (InputStream is = getClass().getResourceAsStream("/content-package-template/" + path)) {
      String xmlContent = IOUtils.toString(is);
      for (Map.Entry<String, Object> entry : metadata.getVars().entrySet()) {
        xmlContent = StringUtils.replace(xmlContent, "{{" + entry.getKey() + "}}",
            StringEscapeUtils.escapeXml10(entry.getValue().toString()));
      }
      zip.putNextEntry(new ZipEntry(path));
      try {
        zip.write(xmlContent.getBytes(Charsets.UTF_8));
      }
      finally {
        zip.closeEntry();
      }
    }
  }
1144830
function save(template, distpath) {
  var data = generate(template);
  var dir = path.dirname(distpath);

  mkdirp(dir, function(err) {
    if(err) {
      console.log(err.message);
      return;
    }

    fs.writeFile(distpath, JSON.stringify(data, null, 2), function(err) {
      if(err) {
        console.log(err.message);
        return;
      }
    });

  });

}
550031
def gen_template_files(path):
    "  "

    path = path.rstrip(op.sep)
    for root, _, files in walk(path):
        for f in filter(lambda x: not x in (TPLNAME, CFGNAME), files):
            yield op.relpath(op.join(root, f), path)
469350
@Override
	protected Reader generateResource(String path, GeneratorContext context) {

		Reader reader = helper.createResource(context);

		String filePath = helper.getFilePath(path);
		if (filePath != null) {
			long lastModified = rsHandler.getLastModified(filePath);
			FilePathMapping fMapping = new FilePathMapping(filePath, lastModified);
			addLinkedResources(path, context, Arrays.asList(fMapping));
		}

		return reader;
	}
952915
public void createCustomArchive(String destArchivePath, String homePath, String templateArchivePath, String templateFilename)
    {
        Record recUser = this.getMainRecord();
        Map<String,String> map = new HashMap<String,String>();
        map.put("${email}", recUser.getField(UserInfo.USER_NAME).toString());
        Date date = new Date();   // Today
        DateField dateField = new DateField(null, null, -1, null, null);
        dateField.setDate(date, DBConstants.DISPLAY, DBConstants.INIT_MOVE);
        map.put("${today}", dateField.toString());
        dateField.free();
        
        URL url = this.getTask().getApplication().getResourceURL(templateFilename, null);
        StringBuilder sb = new StringBuilder(Utility.transferURLStream(url.toString(), null));
        sb = Utility.replace(sb, map);
        String templateFile = Utility.addToPath(destArchivePath, "fixdemo.xsl");
        PrintWriter out = null;
        try {
            File file = new File(templateFile);
            file.getParentFile().getParentFile().mkdirs();  // .tourgeek
            file.getParentFile().mkdirs();  // Folder
            file.createNewFile();
            out = new PrintWriter(file);
        } catch (FileNotFoundException e) {} catch (IOException e) {
            e.printStackTrace();
        }
        if (out != null)
        {
            out.print(sb);
            out.close();
            
            // First, make sure the base demo files exist in the file system
            String workDir = templateArchivePath;
            if (workDir.lastIndexOf(File.separator) != -1)  // Always
                workDir = workDir.substring(workDir.lastIndexOf(File.separator) + 1);
            String workDirPath = Utility.addToPath(homePath, workDir);
            this.populateSourceDir(templateArchivePath, workDirPath);
            
            // Run the xslt against the base demo files.
            Map<String, Object> properties = new HashMap<String, Object>();
            properties.put("sourceDir", workDirPath);
            properties.put("destDir", destArchivePath);
            properties.put("extension", "xml");
            properties.put("filter", ".*");   // Hack (filter is a bad name since it it used in many places)
            properties.put("listenerClass", XMLScanListener.class.getName());
            properties.put("converterPath", templateFile);
            BaseProcess process = new ConvertCode(this.getTask(), null, properties);
            process.run();
            process.free();
        }
    }
958579
function generateMakefile(testFiles, targetPath, callback) {
  var template = new templates.Template('Makefile.magic');
  var fullPath = path.join(targetPath, 'Makefile');
  var context = {
    test_files: testFiles.join(' \\\n ')
  };

  if (path.existsSync(fullPath)) {
    callback(new Error(sprintf('File "%s" already exists', fullPath)));
    return;
  }

  async.waterfall([
    template.load.bind(template),

    function render(template, callback) {
      template.render(context, callback);
    },

    function save(output, callback) {
      fs.writeFile(fullPath, output.join(''), callback);
    }
  ], callback);
}
688500
function generateCustomOutput(outputConfig) {

			// Accesses context
			var context = prepareBaseTemplateContext();
			_.extend(context, outputConfig.context);

			// Prepares config attributes related to template filepath
			var templatePath = outputConfig.template;
			var extension = path.extname(templatePath);
			var syntax = outputConfig.syntax || '';

			// Renders template with given context
			var template = readTemplate(templatePath, syntax, extension);
			var output = renderTemplate(template, context);

			// Prepares config attributes related to destination filepath
			var dest = outputConfig.dest || o.dest;

			var filepath;
			var destParent;
			var destName;

			if (path.extname(dest) === '') {
				// If user specifies a directory, filename should be same as template
				destParent = dest;
				destName = path.basename(outputConfig.template);
				filepath = path.join(dest, destName);
			}
			else {
				// If user specifies a file, that is our filepath
				destParent = path.dirname(dest);
				filepath = dest;
			}

			// Ensure existence of parent directory and output to file as desired
			mkdirp.sync(destParent);
			fs.writeFileSync(filepath, output);
		}
199147
private TeaServletTemplateSource createTemplateSource(
                                         ContextSource contextSource) {
        return TeaServletTemplateSource.createTemplateSource(
            getServletContext(),
            (TeaServletContextSource) contextSource,
            getProperties().subMap("template"),
            getLog());
    }
927707
function(dirpath) {
    try {

      // Make the directory under the app
      if (dirpath !== '/') {
        FS.mkdirSync(Path.join('.', appPath, dirpath));
      }

      // Read the template directory
      var templateDir = Path.join(__dirname, '../template/app', dirpath);
      var files = FS.readdirSync(templateDir);
      files.forEach(function(file) {
        var fullFile = Path.join(templateDir, file);
        var stat = FS.statSync(fullFile);
        if (stat.isDirectory()) {
          // Go into it
          outputDir(Path.join(dirpath, file));
        }
        else {
          outputFile(dirpath, file);
        }
      });

    } catch(e) {
      logger.fatal('Template', 'Cannot process template directory: ' + dirpath + '. reason: ', e.toString());
      process.exit(1);
    }
  }
488513
def process_templates(input_dir, target_dir, context):
    
    if not target_dir.endswith('/'):
        target_dir = "{}/".format(target_dir)
    if not os.path.exists(target_dir):
        LOGGER.info('Creating: {}'.format(target_dir))
        os.makedirs(target_dir)
    replicate_directory_tree(input_dir, target_dir)
    templates = find_templates(input_dir)
    for templ in templates:
        output_file = templ.replace(input_dir, target_dir)
        output_file = output_file[:-len('.mustache')]
        render_template(templ,  output_file, context)
851414
function(dirpath, file) {
    var templateFile = Path.join(__dirname, '../template/app', dirpath, file),
        outputFile = Path.join(appPath, dirpath, file);
    try {
      var template = new Template({text: FS.readFileSync(templateFile).toString(), watchFile:false});
      FS.writeFileSync(outputFile, template.apply(templateParams));
    } catch(e) {
      logger.fatal('Template', 'Cannot process template file: ' + templateFile + '. reason: ', e.toString());
      process.exit(1);
    }
  }