Bro*_*ams 3 javascript variables cdata
CDATA-blocks非常适合将大块HTML或CSS编码为字符串.但是,我无法弄清楚如何在一个变量值中使用变量值.
例如,请考虑以下JavaScript代码:
var FullName = "Friedrich Hayek";
var ProfileCode = (<><![CDATA[
<div id="BigHonkingChunkO_HTML">
...Lot's o' code...
Name: $FullName$
Birth: $Birthdate$
...Lot's o' code...
... $FullName$ ...
...Lot's o' code...
</div>
]]></>).toString ();
Run Code Online (Sandbox Code Playgroud)
如何$FullName$渲染为"Friedrich Hayek"而不是"$ FullName $"?
请注意,有多个变量,每个变量可以在CDATA块中使用几次.
替代代码示例:
var UserColorPref = "red";
var UI_CSS = (<><![CDATA[
body {
color: $UserColorPref$;
}
]]></>).toString ();
Run Code Online (Sandbox Code Playgroud)
希望将颜色属性设置为red.
它够优雅吗?
function replaceVars(content, vars)
{
return content.replace(/\$(\w+)\$/g, function($0, $1)
{
return ($1 in vars ? vars[$1] : $0);
});
}
ProfileCode = replaceVars(ProfileCode, {"FullName" : "Friedrich Hayek"});
Run Code Online (Sandbox Code Playgroud)
如果关联键并不重要,您可以选择使用:
sprintf或vsprintf
编辑
如何使第二个参数可选?
function replaceVars(content, scope) {
if (!scope || typeof scope != "object") {
scope = this;
}
return content.replace(/\$(\w+)\$/g, function($0, $1) {
return ($1 in scope ? scope[$1] : $0);
});
}
// example1
var FullName = "Friedrich Hayek";
ProfileCode = replaceVars(ProfileCode);
// example2
var vars = {"FullName" : "Friedrich Hayek"};
ProfileCode = replaceVars(ProfileCode, vars);
Run Code Online (Sandbox Code Playgroud)