实现生成text / html格式输出的函数的优雅方法是什么?

时间:2012-02-16 17:43:53

标签: javascript jquery design-patterns

我的功能解析文本,抓取部分并生成纯文本电子邮件格式。但它也需要生成html格式。

脑死亡的方法是使用if ... else ...并在每个段落或元素周围添加额外的html标签。但它会违反DRY(不要重复自己)规则。

有没有一种优雅的方法来解决这个问题?

2 个答案:

答案 0 :(得分:2)

正如@Pointy所说,你应该看一下模板。 jQuery templates虽然处于测试阶段,但已经足够好了 - 尽管有很多替代方案可以使用优秀的javascript模板。

在你的情况下,你会做类似的事情:

$.template("textTemplate", "Hi ${name}!\n\nWelcome as a member!");
$.template("htmlTemplate", "<h1>Hi ${name}!</h1><p>Welcome as a member!</p>");

然后像这样使用它们:

var emailText = $.tmpl("textTemplate", data);

// Show the html
$.tmpl("htmlTemplate", data).appendTo("#container");

答案 1 :(得分:0)

您可以使用一系列正则表达式来填充html标记。但请注意,有很多警告不使用RegEx来解析html:RegEx match open tags except XHTML self-contained tags

我会像这样实现正则表达式:

textVAR=YourTextInput;
htmlVAR=textVAR.replace(Reg Ex, "New html tags");// run through a series of RegEx
htmlVAR=htmlVAR.replace(Reg Ex, "New html tags");// fill in html tags where needed
htmlVAR=htmlVAR.replace(Reg Ex, "New html tags");// be sure to add "/g" to your RegEx to make it global
htmlVAR=htmlVAR.replace(Reg Ex, "New html tags");
alert(htmlVAR);

更多资源: 查找网址很困难:http://www.codinghorror.com/blog/2008/10/the-problem-with-urls.html

考虑使用PHP - 这是查找换行符的好资源:http://us2.php.net/nl2br