利用模板template动态渲染jsp页面

时间:2022-02-13 11:18:16

一、场景

在js中写html简直是噩梦,刚进新公司,在codereview的时候得知可以通过将html模板写在jsp页面,然后由js调取模板,利用replace()方法替换传值的方式避免在js中拼接html代码,尝试后,成功利用这种方式完成一个模块的增删查改。

二、具体方式

1. 在jsp页面编写模板,以花括号放置待替换的值

注意定义模板type="text/template"

<body>
<form id="MainDataBills" >
<input type="hidden" id="mainId" value="${ceMainDataBillsVO.id}" />
<!-- headLegend模板 -->
<script type="text/template" id="headTemplate">
<fieldset class="fieldset" id="headFieldset">
<legend id="mainLegend" class="mainLegend">数据单号:{databillsNo}</legend>
</script>
<script type="text/template" id="mainTemplate">
<div class="dlg-backbuttons" style="text-align: center">
<a class="easyui-linkbutton" id="submitButton" onclick="summitWholeDataBillsInCheck()"
data-options="iconCls:'icon-redo'">提交</a>
<a class="easyui-linkbutton" id="returnMainButton" onclick="rejectWholeDataBillsInCheck()"
data-options="iconCls:'icon-undo'">整体驳回</a>
</div>
<table class="fieldsetMainTable" id="mainDataBillsTable">
<tr>
<td class="fieldsetMainTableTd">:</td>
<td id="countTdId">{count}</td>
</tr>
<tr>
<td class="fieldsetMainTableTd">:</td>
<td id="ceCorrSumTdId">{ceCorrSum}</td>
</tr>
<tr>
<td class="fieldsetMainTableTd">:</td>
<td>{planeno}</td>
</tr>
<tr>
<td class="fieldsetMainTableTd">:</td>
<td>{rcLevel}</td>
</tr>
<tr style="display:none">
<td id="subCountTdId">{subCount}</td>
<td></td>
</tr>
</table>
</script>

2. 在js文件中根据id获取该模板,转换为html格式,用raplace替换需要动态显示的值

    //获取head模板,作为headHtml
var headHtml = $("#headTemplate").html();
headHtml = headHtml.replace(/{databillsNo}/g,databillsNo); //获取main模板,作为mainHtml
var mainHtml = $("#mainTemplate").html();
mainHtml = mainHtml.replace(/{databillsNo}/g,databillsNo);
mainHtml = mainHtml.replace(/{count}/g,count);
mainHtml = mainHtml.replace(/{planeno}/g,planeno);
mainHtml = mainHtml.replace(/{rcLevel}/g,rcLevel);
mainHtml = mainHtml.replace(/{subCount}/g,subCount);
mainHtml = mainHtml.replace(/{ceCorrSum}/g,ceCorrSum);

3. 将替换后的html格式的数据append到jsp页面中,搞定

        //全部模板相加
var sumHtml = headHtml + mainHtml + subHtmlSum + endHtml;
$('#MainDataBills').append(sumHtml);

三、注意问题

1. 所用前段框架为easyui, 在替换后的jsp中,需要重新渲染,进行相应组件的显示。

$.parser.parse($("#MainDataBills"));

四、存在不足

1. 该范例用了比较多获取父元素、兄弟元素、子元素的语句,后期修改页面结构容易造成错误。

var currentTab = parent.$("#tabs").tabs('getSelected'),

$(e).parent().parent().nextAll().hide();

var iNum = $(e).parent().find('input').eq(0).val();