当前位置: 移动技术网 > IT编程>开发语言>.net > 基于NVelocity的几种内容生成方式汇总

基于NVelocity的几种内容生成方式汇总

2017年12月12日  | 移动技术网IT编程  | 我要评论

建熙是谁,虐杀原形2优化,松本亚希

使用nvelocity也有几个年头了,主要是在我的代码生成工具database2sharp上使用来生成相关代码的,不过nvelocity是一个非常不错的模板引擎,可以用来生成文件、页面等相关处理,非常高效和方便。

它原先是在网站 上维护,不过从0.41后,该网站就不再进行nvelocity更新了,现在可以在网站上获得最新版本的更新,接着版本的更新操作,我们把nvelocity的几种生成文件的操作介绍一下,以便大家进行更深入的了解。

1、基于nvelocity的几种内容生成方式

从上面的图示,我们可以看到,nvelocity的模板化生成包含了3种方式,一种是从文件到文件或者字符串,一种是从字符串到字符串,他们各自的处理方式有所不同,但是都能正确解析里面的内容。

为了更好利用nvelocity的特性,我们对它进行一个初步的辅助类封装。

/// <summary>
/// 基于nvelocity的模板文件生成辅助类
/// </summary>
public class nvelocityhelper
{
protected velocitycontext context;
protected template template;
protected string templatefile;
/// <summary>
/// 存放键值的字典内容
/// </summary>
private dictionary<string, object> keyobjdict = new dictionary<string, object>();
/// <summary>
/// 添加一个键值对象
/// </summary>
/// <param name="key">键,不可重复</param>
/// <param name="value">值</param>
/// <returns></returns>
public nvelocityhelper addkeyvalue(string key, object value)
{
if (!keyobjdict.containskey(key))
{
keyobjdict.add(key, value);
}
return this;
}................

上面的addkeyvalue方法,主要用来为模板引擎添加一些需要绑定在页面上的变量对象,这样页面变量参数的内容就能正确解析出来了。

为了使用nvelocity的各种特性,我们需要在辅助类里面构造模板的相关信息,设置相关参数。

/// <summary>
/// 初始化模板引擎
/// </summary>
protected virtual void inittemplateengine()
{
try
{
//velocity.init(nvelocity_property);
velocityengine templateengine = new velocityengine();
templateengine.setproperty(runtimeconstants.resource_loader, "file");
templateengine.setproperty(runtimeconstants.input_encoding, "utf-8");
templateengine.setproperty(runtimeconstants.output_encoding, "utf-8");
//如果设置了file_resource_loader_path属性,那么模板文件的基础路径就是基于这个设置的目录,否则默认当前运行目录
templateengine.setproperty(runtimeconstants.file_resource_loader_path, appdomain.currentdomain.basedirectory);
templateengine.init();
template = templateengine.gettemplate(templatefile);
}
catch (resourcenotfoundexception re)
{
string error = string.format("cannot find template " + templatefile);
logtexthelper.error(error);
throw new exception(error, re);
}
catch (parseerrorexception pee)
{
string error = string.format("syntax error in template " + templatefile + ":" + pee.stacktrace);
logtexthelper.error(error);
throw new exception(error, pee);
}
}

在生成内容之前,需要把相关的对象属性绑定到模板引擎的上下文对象里面。

/// <summary>
/// 初始化上下文的内容
/// </summary>
private void initcontext()
{
context = new velocitycontext();
foreach (string key in keyobjdict.keys)
{
context.put(key, keyobjdict[key]);
}
}

1)根据模板文件构造对应的文件内容

/// <summary>
///根据模板创建输出的文件,并返回生成的文件路径
/// </summary>
public virtual string executefile()
{
string filename = "";
if (template != null)
{
string filepath = checkendbyslash(directoryofoutput);
filename = filepath + filenameofoutput + fileextension;
if (!string.isnullorempty(filepath) && !directory.exists(filepath))
{
directory.createdirectory(filepath);
}
//logtexthelper.debug(string.format("class file output path:{0}", filename));
initcontext();
using (streamwriter writer = new streamwriter(filename, false))
{
template.merge(context, writer);
}
}
return filename;
}

2)根据模板文件构造字符串内容

/// <summary>
/// 根据模板输出字符串内容
/// </summary>
/// <param name="templatefile"></param>
/// <returns></returns>
public string executestring()
{
initcontext(); 
system.io.stringwriter writer = new system.io.stringwriter();
template.merge(context, writer);
return writer.getstringbuilder().tostring();
}

3)根据字符串内容构造字符串输出

/// <summary>
/// 合并字符串的内容
/// </summary>
/// <returns></returns>
public string executemergestring(string inputstring)
{
velocityengine templateengine = new velocityengine();
templateengine.init();
initcontext();
system.io.stringwriter writer = new system.io.stringwriter();
templateengine.evaluate(context, writer, "mystring", inputstring);
return writer.getstringbuilder().tostring();
}

上面几种操作模板输出的方式,其调用代码如下所示。

private void btngeneratefile_click(object sender, eventargs e)
{
string tempalte = "template/template.htm";//相对目录
testinfo info = new testinfo();
info.title = "测试标题";
info.content = "测试内容,这是测试内容";
info.datetime = datetime.now;
nvelocityhelper adapter = new nvelocityhelper(tempalte);
adapter.addkeyvalue("title", "this is a title")
.addkeyvalue("content", "this is a content")
.addkeyvalue("datetime", system.datetime.now)
.addkeyvalue("testinfo", info);
adapter.filenameofoutput = "testtemplate";
string filepath = adapter.executefile();
if (!string.isnullorempty(filepath))
{
process.start(filepath);
}
} 
private void btngenerate_click(object sender, eventargs e)
{
string tempalte = "template/template.htm";//相对目录
testinfo info = new testinfo();
info.title = "测试标题";
info.content = "测试内容,这是测试内容";
info.datetime = datetime.now;
nvelocityhelper adapter = new nvelocityhelper(tempalte);
adapter.addkeyvalue("title", "this is a title")
.addkeyvalue("content", "this is a content")
.addkeyvalue("datetime", system.datetime.now)
.addkeyvalue("testinfo", info);
this.txtcode.text = adapter.executestring();
} 
private void btnmergestring_click(object sender, eventargs e)
{
system.text.stringbuilder builder = new system.text.stringbuilder();
builder.append(
"${title}\r\n" +
"$content\r\n" +
"$digest\r\n" +
"$author\r\n" +
"$keyword\r\n" +
"$datetime\r\n");
nvelocityhelper adapter = new nvelocityhelper();
adapter.addkeyvalue("title", "标题").
addkeyvalue("content", "内容").
addkeyvalue("digest", "摘要").
addkeyvalue("author", "作者").
addkeyvalue("keyword", "关键词").
addkeyvalue("datetime", datetime.now);
this.txtcode.text = adapter.executemergestring(builder.tostring());
}

2、模板引擎nvelocity的几种应用场景

上面的几种操作模板内容的方式,能够在绝大多数情况下满足我们的应用要求,如可以在代码生成工具里面,定义一些自定义的内容模板,然后结合数据库的元数据信息,实现丰富逻辑的代码生成操作。

也可以在一些内容管理的应用上(如文章管理方面),根据输入的内容,实现文章内容的文件生成操作,这个生成后,我们就直接使用文章的文件链接地址就可以了。

或者根据数据信息生成具体的页面,用于套打操作,如下是winform里面的套打处理。

以上所述是小编给大家介绍的基于基于nvelocity的几种内容生成方式汇总,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网