首页 > 编程 > .NET > 正文

有空的时候看看,:)ASP.NET Page Templates

2024-07-10 13:01:56
字体:
来源:转载
供稿:网友
菜鸟学堂:
asp.net page templates
by mike borromeo
what?
a website templating system is a small collection of page templates that contain and control any non page specific (redundant) code and html.
who?
this applies to anyone looking for a flexible method for implementing page templates in asp.net. readers new to templates will find them invaluable. readers trained in the template arts but looking for a better implementation already know the value of templates and hopefully will find the methods described here useful for their specific situation (if not i’d like to hear from you, if so i’d also like to hear from you).
why?
in a one page website page templates would be of little use, but when you start building 5+ page sites life starts to get difficult sans templates. a well designed templating system (and i emphasize well designed) has the following benefits to name a few: more efficient and easier development through the elimination of redundant blocks of code, easier integration of designers and programmer through separation of html and server-side script, and easier development of consistent user interface through forced reuse of ui code.
where & when?
me personally, i would use templates in any site that has more than one page. and really there’s no reason not to, so i suppose these ideas apply everywhere and all the time.
how?
ah how… the fun part. here we’ll take a look at an example of a template and a page that employs the template. the entire collection of files you will need along with a more advanced example is available for download.
so you ask, is it difficult to understand or implement? in a word, no. in two words, heck no. if you can count to ten you can use templates. ok, maybe that’s a bit of an overstatement but nevertheless. you’ll be templating, as it were, in no time. first let’s take a look at a simple example of a page that uses a template (a.k.a. a templated page).
<%@ page language="c#" codebehind="default.aspx.cs" inherits="example._default" %><%@ register tagprefix="example" tagname="template" src="/includes/template.ascx"%><example:template title=”example of page templating” id="template" runat="server" >  <body>    here lies the page content.  </body></example:template>
this is about as simple as a templated page gets. you should have a vague idea what everything here means but i’ll explain everything starting at the top. the page directive isn’t specific to this project so we won’t detail it’s meaning. the register directive simply tells asp.net that we’re going to be using the template located as /includes/template.ascx. what’s that you say? user control? why yes it is. the thinking in making a template a user control is this: you write c# in a c# editor and html in an html editor. obvious? maybe. but i’ve seen templates proposed that are implemented as a custom control (written in a code editor, not an html editor). it’s just easier to write html in the vs .net html editor just as it’s easier to write c# in the c# .net editor and with user controls we’re allowed this luxury. intellisense anyone? you could say sure, you can design the template in the html editor the convert it to c# rendered output but then enters the question of maintainability. no designer i know wants to go in an edit a c# file and recompile the bloody web application. ok, now i’m hearing something about speed concerns? well granted compiled code custom control code is faster than the equivalent user control code but it is said that caching erases all your sins or was it cache is king, or maybe cache and thou shall be saved. whichever the case, by using simple native caching techniques in asp.net you can eliminate many of the slowdowns caused by dynamic pages. however, in the case where a page is generated uniquely for each view and also depending on the site load, speed may be the prevailing factor for which custom control page templates may be the answer. user control versus custom control concerns aside, let’s move on to the beginning of the template tags “<example:template>”. i should mention now that this example template was designed with simplicity in mind and customization should, nay, must be performed by you the reader in order to make this system truly useful. what do i mean by customization? well, take the title attribute for example. you don’t have to be a burt muston to realize the title attribute in the template tag corresponds to the title tag in the resulting html. using our imagination picture something else in addition to the title attribute, perhaps the path to a cascading style sheet, or maybe the keywords for the page that will end up in the meta tag. go nuts with it. use your imagination. i should say of course adding the type of customizations i just mentioned are as easy as proverbial pie and we’ll go over just such a change later. but moving on we see the body tag. body in this case is where the main content for the page goes. note: don’t confuse the body tag here with the body tag in “traditional” pages. in previous version of this system the body tag was called main until i realized that intellisense is fully functional when inside a body tag. at any rate, whatever you put in your body tags will show up in the template where you specify. in the spirit of customizations it should be said that having a body tag is simply a function of the needs of the page. so for example if each page needs a sidebar for navigation or whatnot you can add a sidebar tag that resides on the same level as the body tag in the templated page and likewise can put the contents of the sidebar where ever appropriate in the template. again, go nuts and use your imagination… more examples to come.
ok, so i’ll bet you’re saying mike, i can handle this no problem. good, because we’re moving on to the template itself. i’ll just put the entire template file here and we’ll sort it all out afterwards.
<%@ control language="c#" codebehind="template.ascx.cs" inherits="halloffame.includes.template" %><html>  <head>    <title>      <%=this.title%>    </title>    <script runat="server">          /// <summary>      /// insert the body the user provided in our body placeholder.      /// </summary>      protected override void createchildcontrols()      {        // insert the main content body if available        if( null != body )          body.instantiatein( bodycontainer );      }    </script>  </head>  <body>    <table width="100%" height="100%" border="1">      <tr>        <td colspan="2" height="80"><font size="1">header</font></td>      </tr>      <tr>        <td width="100%" height="100%"></td>        <td>          <asp:placeholder id="bodycontainer" runat="server" />        </td>      </tr>      <tr>        <td colspan="2" height="20"><font size="1">footer</font></td>      </tr>    </table>  </body></html>
the attentive reader will notice that there are only three things special to this page compared to any ordinary asp.net page. first, the <%=this.title%> which lies naturally in the title tag (and i’ll explain just how all this works later). second, the block of server code that contains the function createchildcontrols which basically takes the body content supplied by the templated page and drops it right where the asp:placeholder is waiting. which brings us to the third noteworthy bit of code and that’s the asp:placeholder which like we just mentioned is where the body content goes.
how does all this work? how does the title and body content get transferred to the template object that the user control inherits from? to answer this lets take peek at the code behind and unmask the wizard.
using system;using system.data;using system.drawing;using system.web;using system.web.ui;using system.web.ui.webcontrols;using system.web.ui.htmlcontrols;namespace halloffame.includes{  /// <summary>  ///  the main template for this website.  /// </summary>  [parsechildren(true)]  public abstract class template : usercontrol, inamingcontainer  {    /// <summary>    /// the main content template.    /// </summary>    private itemplate main;    /// <summary>    /// the name of the page.    /// </summary>    private string title;    /// <summary>    /// the main content template.    /// </summary>    public itemplate body    {      get { return this.main; }      set { this.main = value; }    }        /// <summary>    /// the name of the page.    /// </summary>    public string title    {      get { return this.title; }      set { this.title = value; }    }    web form designer generated code  }}
looking at this code we see a couple of familiar faces, namely the body and title properties. and in the world of user controls this is how you expose attributes. so remembering back to the example page we introduced near the beginning which looked something like this
<%@ page language="c#" codebehind="default.aspx.cs" inherits="example._default" %><%@ register tagprefix="example" tagname="template" src="/template.ascx"%><example:template title=”example of page templating” id="template" runat="server" >  <body>    here lies the page content.  </body></example:template>
we see the title is set as a template attribute and the body is set as a sub-tag. and now referring back to the code behind the template the body is of type itemplate and the title is of type string bringing up some good questions. do attributes have to be strings? no, they can be integers any other type asp.net can parse from a string. and what is the itemplate type all about? it tells asp.net that the body property will contain children objects. what is parsechildren and why is it true? the parsechildren c# attribute tells asp.net that this class will be a container for child controls and those should be parsed as opposed to placing everything between the start and end tags in a literalcontrol object. how can i add more sections similar to the body section? simply and easily… by just declaring a member variable of the type itemplate and exposing it via a property. basically copy and paste the body blocks and rename accordingly. then in the template.ascx file place an asp:placeholder and in the createchildcontrols function instantiate the new section in the asp:placeholder. pretty easy, no?
conclusions
during the writing of this article i researched several other methods of doing page templates not only in asp.net but also php and asp. both php and asp have a few that have a large following and they really boil down to the same features similar to those mentioned above. but asp.net allows page templates to be implemented so they appear to be a native looking extension integrating seamlessly with vs .net.
available for download are all the files we discussed here and another more complicated example outlining how to use server controls inside the templated page body. bear in mind however that these examples are very simplified to make for easier digestion. they can and should be expanded and improved upon. if you noticed any errors or misinformation please email me at [email protected] if you have a better or improved upon method of doing page templates in asp.net i would be hearing about it. thanks and come again.
download asptemplates.zip
tools used
visual studio .net and windows 2000 server running iis 5.0 with asp.net 
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表