#SLITERAL主要是用来在源代码中按原来的内容显示出来,比如我们要对SEO优化,必须要编辑title元素和Description的content内容。就需要把一些特殊字符显示在源代码中,如:≥,&,"等特殊符号,这就是SLITERAL的应用场景,按原意显示文本内容。这些内容都不直接显示在页面,主要通过源代码查看具体内容,供搜索引擎使用的。在使用SLITERAL等内容时要保证不出现特殊命令和符号,如果String中包含浏览能解析的元素如javascript脚本,特殊字符,我们在输出时一定要小心。
举例:#set($str="<script type='text/javascript'>window.alert();</script>"),如果我们采用#SLITERAL($str)这样就会弹出提示框。如果直接$str就会正常显示代码。因为vm中会默认把代码进行html encode编码。
先看一下一张简单页面到底包含了那些基本元素
html页面几个元素:
html
|---head
| |---title
| |---meta
|---body
我们知道head中的内容不直接显示在页面上,这就意味着浏览器不会解析这里面的内容。
Body中主要是页面展示内容,浏览器会对这块内容进行解析,包括html解析,javascript解析等。这样我们可以看一下这么一个例子:
<!--testHtml.html->
用浏览器打开,很正常的显示一个提示框,内容是4。我们发现title中的内容正常文本,没有被解析。打开源代码,发现description、keywords的内容也没乱码。
Exodus2网站搭建在vm模板上,vm模板默认会对代码进行html encode编码,这意味着如果有一张vm模板页面解析以后要和上面这张html页面内容一致,必须如下编写:
## testHtml.vm
$rundata.getModuleInfo().setLayoutTemplate(null)
<html>
<head>
<title><scripttype='text/javascript'>window.alert(1);</script></title>
<metaname="description"content="<scripttype='text/javascript'>window.alert(2);</script>"/>
<metaname="keywords"content="<scripttype='text/javascript'>window.alert(3);</script>"/>
</head>
<body>
<scripttype='text/javascript'>window.alert(4);</script>
</body>
</html>
有人会说和html编写一样,的确一样。但是exodus2应用中页面的description,keywords等内容主要是通过变量传入的,所以真正实用的代码应该如下:
## testHtml.vm
$rundata.getModuleInfo().setLayoutTemplate(null)
<html>
<head>
#set($title="<scripttype='text/javascript'>window.alert(1);</script>")
#set($description="<scripttype='text/javascript'>window.alert(2);</script>")
#set($keywords="<scripttype='text/javascript'>window.alert(3);</script>")
<title>#SLITERAL($title)</title>
<metaname="description"content="#SLITERAL($description)"/>
<metaname="keywords"content="#SLITERAL($keywords)"/>
</head>
<body>
<scripttype='text/javascript'>window.alert(4);</script>
</body>
</html>
这个页面的内容解析后与原html内容一致。如果去掉#SLITERAL()解析,内容会被velocity引擎按html编码解析后再转化为html页面,内容如下:
<html>
<head>
<title><script type='text/javascript'>window.alert(1);</script></title>
<metaname="description"content=<scripttype='text/javascript'>window.alert(2);</script>/>
<metaname="keywords"content=<scripttype='text/javascript'>window.alert(3);</script>/>
</head>
<body>
<scripttype='text/javascript'>window.alert(4);</script>
</body>
</html>