Using templates to implement ASP code and page separation _asp Foundation

Source: Internet
Author: User
Each developer with a larger asp-web application design probably has the following experience: ASP code and page HTML confusing difficult points, business logic and display way twisted, make the code difficult to understand, difficult to modify; program writing must be a project bottleneck after art Integration of the program code and HTML static page, spend a lot of time to get the ideal effect, and as a graphic artist. Indeed, the use of scripting language to develop Web applications is not easy to separate data processing and data display, but in the case of many people cooperation, if the data and display can not be separated, will greatly affect the efficiency of development, professional division of the play.
Other scripting languages, such as JSP, PHP have their own solutions, the ASP's generation of products asp.net also implemented the Code and page, it seems that the direct transition to the ASP is a good choice. But there are always reasons why we cannot or will not give up the ASP to go straight to the. NET Camp. From a corporate point of view, switching languages is a lot of investment, including hiring skilled workers. NET programmer, training the original programmer, the development tool transformation, Development style transformation, interface style change, interface style, software architecture, documentation, development process and so on; this also means that the original code must be rewritten in the new locale to achieve optimal results and stability, and will directly affect the progress of the project during this period, is more likely to cause individual programmers to run away. It seems that the best option is to seek a solution based on the original before you decide to change the language.
PHP through the template to achieve code and page, you can choose to have Fasttemplate, Phplib, Smarty and many other, of which phplib the most impact, use the most. So, we'll just move it to the ASP, it is also good for companies that use PHP and ASP at the same time: first, the Art of processing the page, whether it will be applied to PHP or ASP, the processing is the same, without training; second, when programmers write code, the two languages of the train of thought close or consistent, The same function in two languages to achieve, just copy over to make a few changes to ensure the efficiency and project progress.

1, the design of template class
The implementation code is encapsulated into a template class, which is designed to be compatible with Phplib and makes code easier to manage and extend.
The goal of the template class is to read the displayed HTML code from the template file, replace the dynamic Data in the display code with the data from the ASP program operation, and then output it in a certain order. In which, the replacement part can be set freely. Therefore, it must complete the following tasks:
• Read the displayed HTML code from the template file.
• Combine the template file with the actual generated data to produce the results of the output.
• Allow multiple templates to be processed at the same time.
• Allow nesting of templates.
• Allows processing of a separate part of the template.

Implementation method:
Use FSO to read template files
Using regular substitution to implement template file and data binding
Processing multiple templates is implemented using array storage.
The main idea of nesting of templates is that the template and output (any intermediate analysis results) are treated equally, and can be replaced.
The processing of the individual part is done by setting the callout in the template file and then combining the annotation in the regular substitution to control the partial substitution.

2, the realization of the template class
Before giving the specific code, first list the main functions, phplib friends should be familiar with this:
1) Public Sub set_root (ByVal Value) set template default directory
2 public Sub set_file (ByVal handle,byval filename) Read file
3 Public Sub Set_var (ByVal Name, ByVal Value, ByVal Append) Set mapping data-replace variable
4 Public Sub Unset_var (ByVal Name) Cancel data map
5 Public Sub Set_block (ByVal Parent, ByVal Blocktag, ByVal Name) set data block
6 Public Sub set_unknowns (ByVal unknowns) setting tag handling without specifying mappings
7 Public Sub Parse (ByVal Name, ByVal Blocktag, ByVal Append) Execute template file and data combination
8 public Sub P (ByVal Name) output processing results

Implementation code:
<%
'=======================================================================
' CLASS name:kkttemplate ASP page Template Object
' Design by: Peng
' Date:2004-07-05
' website:http://kacarton.yeah.net/
' Email:kacarton@sohu.com
'
' This object uses the Set_var, Set_block, and other naming methods to be compatible phplib
'=======================================================================

Class kkttemplate

Private M_filename, M_root, m_unknowns, M_lasterror, M_haltonerr
Private M_valuelist, M_blocklist
Private M_regexp
' Constructor
Private Sub Class_Initialize
Set m_valuelist = CreateObject ("Scripting.Dictionary")
Set m_blocklist = CreateObject ("Scripting.Dictionary")
Set m_regexp = New RegExp
M_regexp.ignorecase = True
M_regexp.global = True
M_filename = ""
M_root = ""
m_unknowns = "Remove"
M_lasterror = ""
M_haltonerr = True
End Sub

' destructor
Private Sub Class_Terminate
Set M_regexp = Nothing
Set m_blockmatches = Nothing
Set m_valuematches = Nothing
End Sub

Public Property Get ClassName ()
ClassName = "Kkttemplate"
End Property

Public Property Get Version ()
Version = "1.0"
End Property

Public Sub About ()
Response.Write ("Kkttemplate ASP page template class <br>" & VbCrLf &_
"Program Design: Peng 2004-07-05<br>" & VbCrLf &_
"Personal site: <a href= ' http://kacarton.yeah.net ' >http://kacarton.yeah.net<;/a><br>" & VbCrLf &_
"E-mail: <a href= ' mailto:kacarton@sohu.com ' >kacarton@sohu.com</a><br>")
End Sub

' Check if the directory exists
Public Function folderexist (ByVal path)
Dim FSO
Set fso = CreateObject ("Scripting.FileSystemObject")
Folderexist = fso. FolderExists (Server.MapPath (path))
Set FSO = Nothing
End Function
' Read the contents of the file
Private Function LoadFile ()
Dim Filename, FSO, Hndfile
Filename = M_root
If right (filename, 1) <> "/" and Right (filename, 1) <> "\" Then filename = filename & "/"
filename = Server.MapPath (filename & m_filename)
Set fso = CreateObject ("Scripting.FileSystemObject")
If not FSO. FileExists (Filename) Then showerror ("Template file" & M_filename & "does not exist!")
Set hndfile = FSO. OpenTextFile (Filename)
LoadFile = Hndfile.readall
Set Hndfile = Nothing
Set FSO = Nothing
If loadfile = "" Then showerror ("Cannot read template file & m_filename &" or file is empty! ")
End Function

' Handling Error messages
Private Sub ShowError (ByVal msg)
M_lasterror = Msg
Response.Write "<font color=red style= ' font-size;14px ' ><b> template error: ' & msg & ' </b></font> <br> "
If M_haltonerr Then Response.End
End Sub

' Set template file default directory
' Ex:kktTemplate.set_root ("/tmplate")
' Kkttemplate.root = '/tmplate '
' root = Kkttemplate.get_root ()
' Root = Kkttemplate.root
' Using a naming method like Set_root to be compatible with Phplib, the following will no longer repeat the description
Public Sub set_root (ByVal Value)
If not Folderexist (value) Then ShowError (value & "is not a valid directory or directory does not exist!")
M_root = Value
End Sub
Public Function Get_root ()
Get_root = M_root
End Function
Public Property Let Root (ByVal Value)
Set_root (Value)
End Property
Public Property Get Root ()
Root = M_root
End Property

' Set up template files
' Ex:kktTemplate.set_file ("Hndtpl", "index.htm")
' This class does not support multiple template files, handle are reserved for compatible phplib
Public Sub set_file (ByVal handle,byval filename)
M_filename = FileName
M_blocklist.add Handle, LoadFile ()
End Sub
Public Function Get_file ()
Get_file = M_filename
End Function
' Public Property Let File (handle, filename)
' Set_file handle, filename
' End Property
' Public Property Get File ()
' File = M_filename
' End Property

' Sets the way to handle unspecified tags, with three kinds of keep, remove, comment
Public Sub set_unknowns (ByVal unknowns)
M_unknowns = unknowns
End Sub
Public Function get_unknowns ()
get_unknowns = m_unknowns
End Function
Public Property Let unknowns (ByVal unknown)
M_unknowns = Unknown
End Property
Public Property Get Unknowns ()
unknowns = m_unknowns
End Property

Public Sub Set_block (ByVal Parent, ByVal Blocktag, ByVal Name)
Dim matches
M_regexp.pattern = "<!--\s+begin" & Blocktag & \s+--> ([\s\s.] *) <!--\s+end "& Blocktag &" \s+--> "
If not m_blocklist.exists (parent) Then ShowError (unspecified block tag & Parent)
Set matches = M_regexp.execute (M_blocklist.item (Parent))
For the Match in matches
M_blocklist.add Blocktag, match.submatches (0)
M_blocklist.item (parent) = Replace (M_blocklist.item (parent), Match.value, "{" & Name & "}")
Next
Set matches = Nothing
End Sub

Public Sub Set_var (ByVal Name, ByVal Value, ByVal Append)
Dim Val
If IsNull (Value) Then val = "" Else val = Value
If m_valuelist.exists (Name) Then
If Append Then m_valuelist.item (name) = M_valuelist.item (name) & Val _
Else M_valuelist.item (Name) = Val
Else
M_valuelist.add Name, Value
End If
End Sub

Public Sub Unset_var (ByVal Name)
If m_valuelist.exists (name) Then M_valuelist.remove (name)
End Sub

Private Function instancevalue (ByVal blocktag)
Dim Keys, I
Instancevalue = M_blocklist.item (Blocktag)
Keys = M_valuelist.keys
For I=0 to M_valuelist.count-1
Instancevalue = Replace (Instancevalue, "{" & Keys (i) & "}", M_valuelist.item (keys (i))
Next
End Function

Public Sub Parse (ByVal Name, ByVal Blocktag, ByVal Append)
If not m_blocklist.exists (blocktag) Then ShowError ("Unspecified block Tags" & Parent)
If m_valuelist.exists (Name) Then
If Append Then m_valuelist.item (name) = M_valuelist.item (name) & Instancevalue (Blocktag) _
Else M_valuelist.item (Name) = Instancevalue (Blocktag)
Else
M_valuelist.add Name, Instancevalue (Blocktag)
End If
End Sub

Private Function Finish (ByVal content)
Select Case M_unknowns
Case "Keep" finish = Content
Case "Remove"
M_regexp.pattern = "\{[^ \t\r\n}]+\}"
finish = m_regexp.replace (content, "")
Case "comment"
M_regexp.pattern = "\{([^ \t\r\n}]+) \}"
finish = m_regexp.replace (content, "<!--Template Variable $ undefined-->")
Case Else finish = content
End Select
End Function

Public Sub P (ByVal Name)
If not m_valuelist.exists (name) Then showerror ("Nonexistent tags" & name)
Response.Write (M_valuelist.item (Name))
End Sub
End Class
%>

3, the use of examples
Here are three examples to illustrate.
1) Simple value substitution
Template file is Mytemple.tpl, content:
Congratulate! You won a {Some_color} Ferrari!
</body>

The following is the ASP code (kktTemplate.inc.asp is the template class given above):
<!--#INCLUDE virtual= "kktTemplate.inc.asp"-->
<%
Dim My_color, Kkt
My_color = "Red"
Set kkt = new Kkttemplate ' Create template Object
Kkt.set_file "Hndkkttemp", "MYTEMPLE.TPL" to set and read the template file Mytemple.tpl
Kkt.set_var "Some_color", My_color, False ' Set template variable Some_color = my_color value
Kkt.parse "Out", "hndkkttemp", false ' template variable out = processed file
KKT.P "out" output out of the content
Set kkt = Nothing ' destroys template object
%>

The output after execution is:
Congratulate! You won a red Ferrari!
</body>


2 Example of circular block demo
Template file Mytemple2.tpl:
<table cellspacing= "2" border= "1" ><tr><td> below animals which one do you like </td></tr>
<!--BEGIN Animallist-->
<tr><td><input type= "Radio" name= "CHK" >{animal}</td></tr>
<!--end Animallist-->
</table>
</body>

ASP code:
<!--#INCLUDE virtual= "kktTemplate.inc.asp"-->
<%
Dim animal, Kkt, I
Animal = Array ("Piggy", "Puppy", "cockroach")
Set kkt = new Kkttemplate
Kkt.set_file "Hndkkttemp", "MYTEMPLE2.TPL"
Kkt.set_block "Hndkkttemp", "animallist", "list"
For i=0 to UBound (animal)
Kkt.set_var "Animal", Animal (i), false
Kkt.parse "List", "Animallist", True
Next
Kkt.parse "Out", "hndkkttemp", False
KKT.P "Out"
Set kkt = Nothing
%>

Execution results:
<table cellspacing= "2" border= "1" ><tr><td> below animals which one do you like </td></tr>
<tr><td><input type= "Radio" name= "CHK" > Piggy </td></tr>
<tr><td><input type= "Radio" name= "chk" > Puppy </td></tr>
<tr><td><input type= "Radio" name= "Chk" > Xiao Qiang </td></tr>
</table>
</body>


3 Nested block Demo
Template file Mytemple3.tpl:
<body><table width= "border=" 1 "bordercolor=" #000000 ">
<tr><td><div align= "center" >{myname} test </div></td></tr>
<tr><td> my zoological and botanical Gardens:</td> </tr>
<!--BEGIN Animallist-->
<tr><td>{animal}</td></tr>
<!--BEGIN Plantlist-->
<tr><td> {plant}</td></tr>
<!--end Plantlist-->
<!--end Animallist-->
</table>
</body>

ASP code:
<!--#INCLUDE virtual= "kktTemplate.inc.asp"-->
<%
Dim My_color, Kkt, myname, animal, plant
Set kkt = new Kkttemplate
MyName = "Kkttemplate block test ..."
Animal = Array ("Animal", "plant")
Plant = Array ("Piggy", "small white", "cockroach"), Array ("Rose", "Sunflower"))

Kkt.set_file "Hndkkttemp", "MYTEMPLE3.TPL"
Kkt.set_var "MyName", MyName, False
Kkt.set_block "Hndkkttemp", "Animallist", "a"
Kkt.set_block "Animallist", "Plantlist", "P"

For i=0 to UBound (animal)
Kkt.set_var "Animal", Animal (i), False
Kkt.unset_var "P"
' Kkt.set_var ' P ', ' ', false
For j=0 to UBound (plant (i))
Kkt.set_var "Plant", Plant (i) (j), False
Kkt.parse "P", "Plantlist", True
Next
Kkt.parse "A", "animallist", True
Next
Kkt.parse "Out", "hndkkttemp", False
KKT.P "Out"
%>

Execution results:
<body><table width= "border=" 1 "bordercolor=" #000000 ">
<tr><td><div align= "Center" >kkttemplate Block test ... Testing </div></td></tr>
<tr><td> my zoological and botanical Gardens:</td> </tr>
<tr><td> Animal </td></tr>
<tr><td> Piglets </td></tr>
<tr><td> Small white </td></tr>
<tr><td> Xiao Qiang </td></tr>
<tr><td> Plants </td></tr>
<tr><td> Rose </td></tr>
<tr><td> Sunflower </td></tr>
</table>
</body>


All the code mentioned in this article can be downloaded from here: Http://www.freewebs.com/kacarton/web/kktTemplate.rar (3.53K)


4. Summary
This paper mainly introduces the method of using template class to separate code from the page based on ASP, and of course, there are other better solutions. This article aims to stimulate readers, web development to participate in, more valuable advice, more exchanges and common progress!
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.