Every developer who has performed large-scale ASP-web application design has the following experiences: It is difficult to confuse ASP code with HTML, and the business logic and display method are twisted, this makes the code hard to understand and modify; programming must become a project bottleneck after the artist; when integrating the program code and HTML static pages, it takes a lot of time to achieve the desired effect, also made an artist. Indeed, it is not easy to separate data processing from data display when developing Web applications using scripting language. However, when multiple people work together, if data and display cannot be separated, the development efficiency will be greatly affected and the professional division of labor will be realized.
Other scripting languages, such as JSP and PHP, all have their own solutions. asp is the last generation of ASP products. net also implements code and pages, and it seems that the direct transition to ASP is a good choice. However, there is always one or another reason that we cannot or cannot give up ASP and go straight to the. NET camp. From the company's perspective, language conversion is a lot of investment, including hiring experts. net programmers, training original programmers, development tool transformation, development style transformation, interface style transformation, interface style, software architecture, documentation, development process, and so on; this also means that the original code must be rewritten in the new language environment to achieve the best effect and stability. At the same time, it will directly affect the project progress during this time period, and may lead to the departure of individual programmers. Therefore, before you decide to change the language, it is the best choice to seek a solution based on the original.
PHP uses templates to implement code and pages. You can choose from fasttemplate, phplib, and smarty among other options. Among them, phplib has the greatest impact and the most use. In this case, we can directly move it to ASP, which is of great benefit to companies that use PHP and ASP at the same time: 1. When the artist processes the page, whether PHP or ASP will be applied, the processing method is the same, and training is not required. 2. When programmers write code, the idea of the two languages is similar or consistent. When the same function is implemented in the two languages, you only need to copy the file and make a slight modification to ensure work efficiency and project progress.
1. Template Class Design
The implementation code is encapsulated into a template class to be compatible with phplib and facilitate code management and expansion.
The purpose of the template class is to read the displayed HTML code from the template file and replace the dynamic data in the displayed code with the data obtained by ASP operations, and then output in a certain order. The replacement part can be set freely. Therefore, it must complete the following tasks:
· Read the HTML code used for display from the template file.
· Combine template files with actually generated data to generate output results.
· Multiple templates can be processed simultaneously.
· Allows template nesting.
· Allows processing of a separate part of the template.
Implementation Method:
Use FSO to read template files
Use regular expression replacement to combine template files and data
Processing multiple templates is implemented using array storage.
The main idea of implementing template Nesting is to treat the template and the output (any intermediate analysis results) equally, and they can be replaced.
Individual parts are processed by setting tags in the template file, and then using tags in regular expression replacement to control partial replacement.
2. Implementation of the template class
Before providing specific code, list the main functions. phplib users should be familiar with this:
1) Public sub set_root (byval value) sets the default template directory
2) Public sub set_file (byval handle, byval filename) read the file
3) Public sub set_var (byval name, byval value, byval append) set ing data-replace variable
4) Public sub unset_var (byval name) cancels data ing
5) Public sub set_block (byval parent, byval blocktag, byval name) sets the data block
6) Public sub set_unknowns (byval unknowns) sets the tag Processing Method for unspecified Mappings
7) Public sub parse (byval name, byval blocktag, byval append) Execution template file and data combination
8) Public sub P (byval name) output processing result
Implementation Code: <%
'================================================ ======================================
'Class name: kkttemplate ASP page template object
'Design by: Peng Guohui
'Date: 2004-07-05
'Website: http://kacarton.yeah.net/
'Email: kacarton@sohu.com
'
'The naming methods such as set_var and set_block are used in this object to be compatible with 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 Guohui <br>" & vbcrlf &_
"Personal website: <a href = 'HTTP: // kacarton.yeah.net '> http://kacarton.yeah.net </a> <br>" & vbcrlf &_
"Email: <a href = 'mailto: kacarton@sohu.com '> kacarton@sohu.com </a> <br> ")
End sub
'Check whether 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 File Content
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 ("the template file cannot be read" & m_filename & "or the file is empty! ")
End Function
'Handle 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 the default directory of the template file
'Ex: kkttemplate. set_root ("/tmplate ")
'Kttemplate. Root = "/tmplate"
'Root = kkttemplate. get_root ()
'Root = kkttemplate. Root
'Use a naming method like set_root to be compatible with phplib. The following will not be repeated
Public sub set_root (byval value)
If not folderexist (value) Then showerror (Value & "is not a valid directory or the 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 the Template File
'Ex: kkttemplate. set_file ("hndtpl", "index.htm ")
'This class does not support multiple template files. Handle is retained because it is compatible with 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 processing method for unspecified tags, including keep, remove, and 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 + 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 each 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 tag" & 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 $1 undefined --> ")
Case else finish = content
End select
End Function
Public sub P (byval name)
If not m_valuelist.exists (name) Then showerror ("nonexistent tag" & name)
Response. Write (finish (m_valuelist.item (name )))
End sub
End Class
%>
3. Example
The following are three examples.
1) Simple Value Replacement
The template file is mytemple. TPL. content:
<HTML> <title> simple ASP template replacement </title> <body>
Congratulations! You win 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 "hndkttemp", "mytemple. TPL" 'sets and reads the template file mytemple. TPL
Kkt. set_var "some_color", my_color, false ': set the value of the template variable some_color = my_color.
Kkt. parse "out", "hndkkttemp", false' template variable out = processed file
Kkt. P "out" 'output the out content
Set kkt = nothing 'Destroy template object
%>
After execution, the output is: <HTML> <title> simple replacement of ASP templates </title> <body>
Congratulations! You win a red Ferrari!
</Body>
2) Example of loop Blocks
Template File mytemple2.tpl: <HTML> <title> Asp template-block demonstration </title> <body>
<Table cellspacing = "2" border = "1"> <tr> <TD> which of the following animals 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 ("Piglet", "Puppy", "Xiaoqiang ")
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 result: <HTML> <title> Asp template-block demonstration </title> <body>
<Table cellspacing = "2" border = "1"> <tr> <TD> which of the following animals do you like? </TD> </tr>
<Tr> <TD> <input type = "radio" name = "Chk"> pig </TD> </tr>
<Tr> <TD> <input type = "radio" name = "Chk"> puppy </TD> </tr>
<Tr> <TD> <input type = "radio" name = "Chk"> Xiaoqiang </TD> </tr>
</Table>
</Body>
3) nested block demonstration
Template File mytemple3.tpl: <HTML> <title> Asp template-nested block demonstration </title>
<Body> <Table width = "400" border = "1" bordercolor = "#000000">
<Tr> <TD> <Div align = "center"> {myname} test </div> </TD> </tr>
<Tr> <TD> my botanical garden: </TD> </tr>
<! -- Begin animallist -->
<Tr> <TD >{ animal} </TD> </tr>
<! -- Begin plantlist -->
<Tr> <TD> {plant} </TD> </tr>
<! -- End plantlist -->
<! -- End animallist -->
</Table>
</Body>
</Html>
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 (Array ("", "", ""), array ("Rose", "sunflower "))
Kkt. set_file "hndkkttemp", "mytemple3.tpl"
Kkt. set_var "myname", myname, false
Kkt. set_block "hndkkttemp", "animallist", ""
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 result: <HTML> <title> Asp template-nested block demonstration </title>
<Body> <Table width = "400" border = "1" bordercolor = "#000000">
<Tr> <TD> <Div align = "center"> kkttemplate block test... test </div> </TD> </tr>
<Tr> <TD> my botanical garden: </TD> </tr>
<Tr> <TD> animal </TD> </tr>
<Tr> <TD> pig </TD> </tr>
<Tr> <TD> Xiao Bai </TD> </tr>
<Tr> <TD> Xiaoqiang </TD> </tr>
<Tr> <TD> plants </TD> </tr>
<Tr> <TD> rose </TD> </tr>
<Tr> <TD> sunflower </TD> </tr>
</Table>
</Body>
</Html>
Download example:
/Files/Maxie/kkttemplate.rar