如何用html做一个彩色字段,如何Html转义模板字段

本文介绍了一个使用StringTemplate进行HTML编码的示例程序。通过自定义渲染器实现了变量的HTML转义,日期格式化等功能,并展示了如何加载模板、设置变量及渲染输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;

using System.Globalization;

using System.Security;

using System.Text;

using System.Web;

using Antlr4.StringTemplate;

class Program

{

static void Main(string[] args)

{

TemplateGroup g = new TemplateGroup('$', '$');

g.RegisterRenderer(typeof(object), new MyTemplateRenderer());

string temp = "$var;format=\"html-encode\"$\n$date;format=\"{0:R}\"$";

Template t = new Template(g, temp);

t.Add("var", "<>");

t.Add("date", DateTime.Now);

Console.WriteLine(t.Render());

Console.ReadLine();

}

}

public class MyTemplateRenderer : IAttributeRenderer

{

public virtual string ToString(object o, string formatString, CultureInfo culture)

{

if (formatString == null) return o.ToString();

switch (formatString) {

case "upper":

return o.ToString().ToUpper(culture);

case "lower":

return o.ToString().ToLower(culture);

case "cap":

string s = o.ToString();

return s.Length > 0 ? Char.ToUpper(s[0], culture) + s.Substring(1) : s;

case "url-encode":

return HttpUtility.UrlEncode(o.ToString(), Encoding.UTF8);

case "xml-encode":

return SecurityElement.Escape(o.ToString());

case "html-encode":

return HttpUtility.HtmlEncode(o);

default:

return String.Format(culture, formatString, o);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值