用ASP写一个支持自定义模板的数据记录输出函数

在.NET中,可以使用多种DATA服务器控件如ListView来显示数据库记录,并且能自定义模板。

在ASP中,没有服务器控件的概念,不过我们可以自己来写一些程序来实现这样的功能。

对于数据库记录的输出,我们可以写这样的函数来完成。它接受4个参数,分别是:

  1. 一个数据库记录集对象 Recordset
  2. 模板标签的头部
  3. 模板标签的重复项目部分
  4. 模板标签的底部

代码示例如下:

    '
    ' 输出结果集,支持自定义模板
    '
    Public Function OutputRSWithTemplate(objRS, header, itemRepeater, footer)
        Dim i, regEx, matches, repeater, j
        
        'On Error Resume Next
        OutputRSWithTemplate = ""
        OutputRSWithTemplate = OutputRSWithTemplate & header
        Set regEx = Server.CreateObject("VBScript.RegExp")
        Set matches = Nothing
        regEx.Global = True
        regEx.IgnoreCase = True
        regEx.Pattern = "<#=\s*([^<#>]*)\s*#>"
        
        '数据行
        If objRS.State > 0 And objRS.RecordCount > 0 Then
            ' 以下这句在分页中必须去掉!!!
            'objRS.MoveFirst
            Set matches = regEx.Execute(itemRepeater)
            For i = 1 To objRS.PageSize
                If objRS.EOF Then
                    Exit For
                End If
                
                repeater = itemRepeater
                For j = 0 To matches.Count - 1 
                    If matches(j).SubMatches.Count > 0 Then
                        repeater = Replace(repeater, matches(j), objRS(Trim(matches(j).SubMatches(0))))
                    Else
                        repeater = Replace(repeater, matches(j), "***")
                    End If
                Next
                
                OutputRSWithTemplate = OutputRSWithTemplate & repeater
                
                If objRS.EOF Then
                    Exit For
                Else
                    objRS.MoveNext
                End If
            Next            
        End If
        
        If Not matches Is Nothing Then
            Set matches = Nothing
        End If
        Set regEx = Nothing
        OutputRSWithTemplate = OutputRSWithTemplate & footer
        
        On Error Goto 0
    End Function

比如在数据库中有一个友情链接表,我们已经将里面的数据查询出来,并放在了一个数据记录集(Recordset)对象(rs)中。我们现在要将这些信息以列表形式显示出来,就可以如下来调用上面的自定义函数:

Dim header, itemRepeater, footer

header = "<div><ul>" 
itemRepeater = "<li><a href=""><#= SiteURL #>"" target=""_blank"" title=""<#= SiteIntro #>""><#= SiteName #></a></li>" 
footer = "</ul></div>"
Response.Write OutputRSWithTemplate(rs, header, itemRepeater, footer)

函数 OutputRSWithTemplate 返回一个字符串,它由我们自己定义的头部、重复项目部分以及底部组成,传递给它的重复项目部分参数itemRepeater,凡是要使用数据库记录集中的数据的,就用 <#= 字段名 #> 的格式来标记,这样,它就能使用数据库记录集中对应的字段的值来替换该标记。

Add comment

Loading