将内容页合并到母版生成完整网页,方便更新页面公共部分如导航条侧边栏等,只需更改母版页所有使用母版页的内容页面都会更新
将head合并到母版的head中,将contentId的内容合并到母版的同名母版页位置
<master master="../masters/master.html">
<head>
<style>
.test {
}
</style>
</head>
<div contentId="maincontent" style="font-size:20px;">
test
</div>
</master>
<!DOCTYPE html>
<html>
<head>
</head>
<body class="layui-layout-body">
<div lay-server-options="{type:'user',name:'test123'}">
{{d.name}}>cache
<div lay-server-options="{type:'user',name:'test123-1'}">{{d.name}}
<div lay-server-options="{type:'user',name:'test123-1-1'}">{{d}}
<div lay-server-options="{type:'user',name:'test123-1-1-1'}">{{d.name}}</div>
</div>
</div>
</div>
<div contentId="maincontent"></div>
<div contentId="subcontent"></div>
</body>
</html>
合并后
<!DOCTYPE html>
<html>
<head>
<style>
.test {
}
</style>
</head>
<body class="layui-layout-body">
<div> test123>cache
<div>test123-1
<div>test123-1-1
<div>test123-1-1-1</div>
</div>
</div>
</div>
<div style="font-size:20px;">
test
</div>
<div contentId="subcontent"></div>
</body>
</html>
C# 代码
//缓存时长
private static readonly XmlCacheLevel cacheLevel = XmlCacheLevel.NoCache;
private static string CalcPath(string basePath, string targetPath)
{
try
{
if (!(basePath.EndsWith("\\") || basePath.EndsWith("/")))
{
if (Path.GetFileName(basePath).IndexOf(".") != -1)
{
basePath = Path.GetDirectoryName(basePath);
}
}
return Path.GetFullPath(Path.Combine(basePath, targetPath));
}
catch
{
throw new Exception("Error File Path");
}
}
//合并母版
private static void CombineMaster(XHtmlAction view, string viewPath)
{
XmlNode root = view.XmlDoc.DocumentElement;
if (root != null && root.Attributes["master"] != null)
{
string masterPath = root.Attributes["master"].Value;
XHtmlAction masterView = new XHtmlAction();
masterPath = CalcPath(viewPath, masterPath);
if (masterView.Load(masterPath, cacheLevel, true))
{
foreach (XmlNode node in root.ChildNodes)
{
if (node.Name.Equals("head", StringComparison.OrdinalIgnoreCase)||
node.Name.Equals("body", StringComparison.OrdinalIgnoreCase))
{
XmlNodeList mNodes = masterView.GetList(node.Name.ToLower());
if (mNodes.Count > 0)
mNodes[0].InnerXml += node.InnerXml;
}
else
{
XmlAttribute nodeAttr = node.Attributes["contentId"];
if (nodeAttr != null)
{
string toContentID = nodeAttr.Value;
if (!String.IsNullOrEmpty(toContentID))
{
var cont = masterView.GetList("*", "contentId", toContentID);
if (cont.Count>0)
{
node.Attributes.Remove(node.Attributes["contentId"]);
masterView.ReplaceNode(node, cont[0]);
}
}
}
}
}
view.LoadXml(masterView.OutXml);
}
}
}
public static XHtmlAction Create(string fullPath)
{
XHtmlAction view = new XHtmlAction(true, false);
if (view.Load(fullPath, cacheLevel, true))
{
if (!view.IsLoadFromCache)
{
//母版页替换
CombineMaster(view, fullPath);
view.RefleshCache(); //更新缓存
}
//加载控件数据
LoadViewData(view);
}
return view;
}
使用的CYQ.Data.Xml; 中的XHtmlAction 处理html数据
CYQ.Data 获取地址