您好,欢迎访问一九零五行业门户网

[QMacros]示例:使用 QMacros 玩转 HTML 模板_html/css_WEB-ITnose

我们在实际开发中,由于各种各样的原因,可能会结合浏览器来实现一些 delphi 本身不好实现的效果。而如果网页是靠拼字符串来完成,显然其效率不是太理想。而如果结合 qmacros ,你会发现一切都变的那么简单。qmacros 的示例中包含了一个新的 html 模板示例代码,我们来解读其中与 qmacros 相关的部分,来看看如何玩转 html 模板。
首先,我们在窗体上包含了一个数据集,数据集中有两个字段:id 和 name,由于在设计期添加了这两个字段,所以在定义中我们可以看到它们分别是 adsdataid 和 adsdataname。为了演示方便,我们在窗体的构造函数中生成了10条测试数据。
接下来,我们来看剩下的源码:
procedure tform1.button1click(sender: tobject);const stabletemplate: qstringw = '' + // '这是一个表格'+ // '编号 姓名
' + // '' + // '
';var amacros: tqmacromanager; ahtmlfile: string;begin amacros := tqmacromanager.create; try amacros.push('title', 'qmacros html表格'); amacros.push('rows', doreplacerows); ahtmlfile := extractfilepath(application.exename) + 'index.html'; savetextw(ahtmlfile, amacros.replace(stabletemplate, '', mrf_parse_params)); webbrowser1.navigate('file:///' + stringreplacew(ahtmlfile, '\', '/', [rfreplaceall])); finally freeandnil(amacros); end;end; procedure tform1.doreplacerows(amacro: tqmacroitem; const aquoter: qcharw);var amacros: tqmacromanager; areplace: tqmacrocomplied; ahelper: tqstringcathelperw;begin amacros := tqmacromanager.create; ahelper := tqstringcathelperw.create; adsdata.disablecontrols; try amacros.push(adsdata, ''); adsdata.first; areplace := amacros.complie(amacro.params[0].asstring, '%', '%'); while not adsdata.eof do begin ahelper.cat(areplace.replace); adsdata.next; end; amacro.value.value := ahelper.value; finally freeandnil(amacros); freeandnil(ahelper); freeandnil(areplace); adsdata.enablecontrols; end;end;
好了,我们来说明一点,我们在示例中直接定义了一个常量字符串stabletemplate,实际上这个东西你完全可以定义到外部文件中,然后在运行时用 loadtextw 加载。后面的步骤就和这个示例一样了。
我们来看 button1click 都做了啥:
创建 tqmacromanager 对象实例 amacros; 入栈了两个宏: title :用来做为表格标题 rows :一个带参数的宏,参数是要重复的html内容 执行 amacros 的替换,并将替换结果保存到当前程序下,命名为 index.html。 用 navigate 函数加载保存的网页,以显示生成的 html 内容。 在这里,宏 title 是一个固定值,而 rows 是一个函数式的宏,由 doreplacerows 来提供进一步处理:
创建必要的实例; 将 adsdata 数据集的字段入栈; 预编译 rows 宏的参数,以便后面重复替换; 循环 adsdata 生成,替换的每一步结果追加到 ahelper 中; 设置宏当前的值为 ahelper.value; 清理局部变量的值; ok,这样子,就完成了上面的模板的替换工作。这里注意,我创建了一个局部的 tqmacromanager 对象的实例,当然你也可以用 button1click 里的 amacros,那样,宏 title 、rows 的值也会被嵌入。
我们看一下实际的运行结果:
其它类似信息

推荐信息