Login

Dynamic content in templates

Versions: n/a, FAQ number: 20, Old FAQ number: 933

Q: Is it possible to have dynamic content in templates for a listing control for examle: Sometimes I would like to show a thumbnail picture in the beginning of a template and sometimes I don't. Is it possible to use for example a condition within a template?

A: You can acomplish this in several ways in .NET and here follows some guidlines and suggestions on how to do it.

 1. Use the Web and Html controls in .NET

In the code behind file you create instances of Labels TableCells, then you add the instances to the Controls class for the desired control.

So how do you access the desired contol? Simply, trap the PreRender event which the listing fires just before it will generate the listing content. The following example adds a label which will be first in the control list of the listing.

  private void NewsList_PreRender(object sender, System.EventArgs e)
  {
      EPiServer.WebControls.NewsList newsList =
         sender as EPiServer.WebControls.NewsList;
  
      Label someLabel = new Label();
      someLabel.Text = "Label added in NewsList_PreRender.";
      someLabel.BackColor = Color.Blue;
      someLabel.ForeColor = Color.White;
      newsList.Controls.Add(someLabel);
  }
 
  private void InitializeComponent()
  {   
      this.Load += new System.EventHandler(this.Page_Load);
      NewsList.PreRender += new System.EventHandler(this.NewsList_PreRender);
  }
 
With the PreRender event you can change the layout before the NewsList renders the content. Another way to change the rendering is that you override the Render() method of the listing class. Take a look in the help for .NET or MSDN online to get instructions how this is done.

2) Another way is to generate the layout run-time: Call a code behind function from the template at DataBind which returns a string with html.

Example:

    aspx:
        <FirstNewsTemplate>
            <%# GenerateFirstNewsTemplateLayout() %>
 
    Code behind:
        string GenerateFirstNewsTemplateLayout()
        {

            // create a html string with for example StringBuilder
            return "<table>... ";    // return the layout as html
        }

EPiTrace logger