JNTemplate 快速入门
作者:翅膀的初衷 来源:本站原创 发布时间:2013-11-27 查看数:62939
首先下载JNTemplate,下载地址可以在 Asp.net模板引擎JNTemplate 开源地址{target="_blank"} 获取!最新版的源代码在GitHub下载,如果只是需要DLL文件,可以 点击此处{target="_blank"} 下载生成好的文件包!
下载完成后解压,DLL文件里面有二个目录,即2.0与4.0,如果你当前项目的.NET Framework 为2.0/3.0/3.5 则将2.0目录下的Jiniannet.JNTemplate.dll拷到项目中,如果是 4.0/4.5/4.5+ 则拷贝4.0目录下的DLL
添加引用后,环境就搭配完成了!我们先在网站根目录新建一个demo.html来当模板,内容如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>$title</title>
</head>
<body>
<h1>图书目录 >> ${class_name}</h1>
<ul>
$foreach(node in book_list)
<li>$node.name ……………………………………………………作者: $node.author</li>
$end
</ul>
</body>
</html>
然后新建一个demo.aspx页面,除第一行外其它的内容全部删除,如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Demo.aspx.cs" Inherits="Demo" %>
转到:demo.aspx.cs,代码如下(具体说明见注释):
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
public partial class Demo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<book> list = new List<book>();
list.Add(new book("平凡的世界", "路遥"));
list.Add(new book("三少爷的剑", "古龙"));
list.Add(new book("雪山飞狐", "金庸"));
list.Add(new book("丰乳肥臀", "莫言"));
JinianNet.JNTemplate.TemplateContext context = new JinianNet.JNTemplate.TemplateContext();
context.Paths.Add(Server.MapPath("~/"));//设置模板目录
//设置前台展现数据
context.TempData["title"] = "jntemplate使用";
context.TempData["class_name"] = "哲学类";
context.TempData["book_list"] = list;
//读取模板内容
string text = System.IO.File.ReadAllText(Server.MapPath("~/demo.html"));
JinianNet.JNTemplate.Template t = new JinianNet.JNTemplate.Template(context, text);
//结果呈现
t.Render(Response.Output);
}
public class book
{
public book(string book_name, string book_author)
{
this._author = book_author;
this._name = book_name;
}
private string _name;
public string name
{
get { return _name; }
set { _name = value; }
}
private string _author;
public string author
{
get { return _author; }
set { _author = value; }
}
}
}
好,一个简单的DEMO就完成了,我们按F5运行一下!结果如下:
图书目录 >> 哲学类
- 平凡的世界 ............................................................作者: 路遥
- 三少爷的剑 ............................................................作者: 古龙
- 雪山飞狐 ............................................................作者: 金庸
- 丰乳肥臀 ............................................................作者: 莫言
是不是很简单,我们发现demo.html里面有一些$开头的文本,这些就是JNTemplate中的标签,相当于占位符,可以理解为asp.net中的 <% 内容 %> , 格式为 ${ 标签内容 },通常都可以简写成 $标签内容
具体的标签用法可以查看 JNTemplate帮助文档{target="_blank"}