Ader templateengine2 original description

Source: Internet
Author: User
Tags closing tag

Http:// Page = templateengine2

AderTemplateengineIs. net class library (written in C #) for generating text output from source template and input parameters. it can be used in your scenarios: website page building, email generation, XML generation, source code generation, etc. it's idea is based on anlr stringtemplate (, but the syntax is based on cold fusion language.

Currently only. Net adertemplateengine works with. NET 2.0 only. There is a back-port to 1.1 available in downloads at the bottom.
This document is for version 2.1 of the engine. You can see version 1 here.
Ader templateengine is released under GNU General Public License.

Here is a very simple template:

Thank You for your order #order.billFirstName# #order.billLastName#.<br>Your Order Total is: #format(, "C")#<br><ad:if test="#order.shipcountry isnot "US"#">Your order will arrive in 2-3 weeks<ad:else>Your order will arrive in 5-7 days</ad:if>

The templates can have expressions, if/elseif/else statement, foreach statement, for statement, set statement and Other templates.

Templates API:There are 2 classes mainly used in template engine: Template and templatemanager.
Template holds a single instance of a template and templatemanager is used for executing templates.
Easiest way of creating templates is by using static methods of template or templatemanager:

Template template = Template.FromString(string name, string data)Template template = Template.FromFile(string name, string filename)

Then you use it to instantilate templatemanager.

TemplateManager mngr = new TemplateManager(template);

Or even easier:

TemplateManager mngr = TemplateManager.FromFile(filename);TemplateManager mngr = TemplateManager.FromString(template);

When using fromstring method, the string passed contains template code. This method can be used to dynamically generate text without having templates in files.
You use setvalue (string name, object value); to add values that can be used within the templates.

mngr.SetValue("customer", new Customer("Tom", "Jackson"));

Then you can refer to customer within the template. You can use any type of object for value. When the value of variable is to be output tostring () method will be called.

Expressions are enclosed with # (hash or pound) characters:
# Firstname #

This example will output value of first name. If you need to output # character, just escape it with another #.
Your SS # Is # ssnumber #

Inside of expression block you can output any variable:
# Somevar #

Access property or field of a variable:
# Somestring. Length #

Property name is not case senstivie. So you can call: # string. Length # Or # string. Length #

Or call a function:
# Trim (somename )#
You can nest property accesses:
# Customer. firstname. Length #
You can also call methods on any objects:
# Firstname. substring (0, 5 )#
# Customer. isvalid ()#

Version 2.1 also allows you to use array access from indexed variables:
# Somearray [3] #-gets 3rd element of Array
# Hastable ["somekey"] #-gets value of "somekey" from hashtable.
You can use array access with any object that has indexer property.

There are several built in functions and additional functions can be easily added. The built in functions are:
Equals (obj1, obj2)-Invokes equals Method on obj1 with obj2 as parameter. Returns Boolean value.

Notequals (obj1, obj2)-Returns! Equals (obj1, obj2). Is equavilant to calling: Not (equals (obj1, obj2 ))

Iseven (Num)-Tests whether number is an even number

Isodd (Num)-Tests whether number is an odd number

Isempty (string)-Test whether string has 0 characters. Same as equals (string. length, 0)

Isnotempty (string)-Tests whether string has at least 1 character.

Isnumber (Num)-Tests whether num is of numeric type

Toupper (string)-Converts string to upper case

Tolower (string)-Converts string to lower case

Isdefined (varname)-Tests whether variable named varname is defined

Ifdefined (varname, value)-Returns value if varname is defined. especiall useful: # ifdefined ("name", name) #-will output value of name if it's defined, otherwise will output nothing

Len (string)-Returns length of string

Tolist (collection, property, delim)-Will convert collection to string with delim as seperator. if you pass property, the value of the property will be evaluated on each element of collection. if you omit property, then the object itself will be used.
Suppose you have list:

ArrayList list = new ArrayList();list.Add("one");list.Add("two");list.Add("three");template.SetValue("mylist", list);

Then in your template:
# Tolist (mylist ,"&")#
The output will be: One & Two & Three

Suppose you have list:

list.Add(new Customer("Tom", "Whatever"));list.Add(new Customer("Henry", "III"));list.Add(new Customer("Tom", "Jackson"));template.SetValue("mylist", list);

Then in template:
# Tolist (mylist, "firstname ",",")#
The output will be: Tom, Henry, Tom

Isnull (OBJ)-Tests whether obj is null

Not (boolvalue)-Returns not (!) Of Boolean Value

IIF (booleanexpression, iftruevalue, iffalsevalue)-Same as booleanexpression? Iftruevalue: iffalsevalue in C #
# IIF (isodd (I), "bgcolor = yellow", "bgcolor = red ")#
Will output bgcolor = yellow if I is odd number and bgcolor = red if I is not odd number

Format (object, formatstring)-Will call tostring (formatstring) on object. object has to implement iformattable interface, otherwise tostring () will be called.
(Suppose total is decimal with value 1208.45)
# Format (total, "C ")#
Will output: $1,208.45

Trim (string)-Will trim String object

Filter (collection, booleanproperty)-Will return new list from collection for those objects whose booleanproperty property evaluates to true

GT (obj1, obj2)-Will return true if obj1> obj2 (obj1 and obj2 must implement icomparable. All numeric types do)

LT (obj1, obj2)-Will return true if obj1 <obj2 (obj1 and obj2 must implement icomparable. All numeric types do)

Compare (obj1, obj2)-Will return-1 If obj1 <obj2, 0 is obj1 = obj2, and 1 If obj1> obj2 (obj1 and obj2 must implement icomparable. All numeric types do)

Or (bool1, bool2)-Will return true if either bool1 or bool2 are true
# Or (equals (state, "Il"), equals (state, "NY") #-returns true if State is either IL or NY

And (bool1, bool2)-Will return true if both bool1 and bool2 are true

Comparenocase (string1, string2)-Will do case insenstive comparison of string1 and string2 and return true if they are equal

Stripnewlines (string)-Will return all \ r \ n instances and replace them with space

Typeof (object)-Will return string representation of the type of object. Ex: typeof ("hello") Return "string". typeof (3) returns int

CINT (value)-Converts value to INTEGER (internally used convert. toint32 from. Net Library)

Cdouble (value)-Converts value to double

Cdate (value)-Converts value to datetime type. You can use this function if you want to create datetime objects. Ex: # cdate ("2005-5-1 ")#

Createtypereference (type)-You can use this function to create references to static types so that you can access static properties or call methods of a static object. it's most useful when Combind with <ad: Set tag (explained below)

#createtypereference("System.Math").Round(3.39789)##createtypereference("System.Math").PI#or<ad:set name="MyMath" value="#createtypereference("System.Math")#" />#MyMath.Round(3.3)##MyMath.PI#

Version 2.1 also adds some operators for common expressions:
Is-Same as calling function equals. Ex: # obj1 is obj2 # Will return true if obj1 is equal to obj2.

Isnot-Same as calling function notequals. Ex: # obj1 isnot obj2 #

And-Used in if expressions tests (same as & in C #)

Or-Same as | in C #

Lt,LTE,GT,GTE-Less than ("<" in C #), less than or equal ("<="), greater than ("> ") and greater than or equal ("> = "). both operands have to implement icomparable interface. when using numeric types, they have to be of the same type. if you want to compare int to double, you have to convert int to double first using cdbl function.

#varOne lt 3##varTwo lte cdbl(3)##varThree gt varFour and varFive gte 5.0#

Built in tags:
You can also conditionally output text based on some expression using special if Tag:

<ad:if test="#booleanexpression#"><ad:elseif test="#bool#"><ad:else></ad:if>

Elseif and else are optional. If test of "if" evaluates to true, then block inside of "if" will be output, otherwise elseif will be tested (if exists) and then else.

<ad:if test=" is "US"#">You are US customer.<ad:else>You are from: country.</ad:if>

If Cust. Country is "us" then the output will be: You are US customer.

You can loop through collection of elements (any object that implements ienumerable Interface) using foreach tag.

<ad:foreach collection="#collection#" var="cust" index="i">#i#: #cust.lastname#, #cust.firstname#</ad:foreach>

Suppose customers is array of customer objects: Customers = Customer ("Tom", "Jackson"), customer ("Mary", "foo ")
The output will be:
1. Jackson, Tom
2. Foo, Mary

During execution, variable name that is passed as VAR attribute will be assigned with element from the collection. index attribute can be omitted, and is used to represent index variable for the loop. it starts with 1 and gets increments with each iteration.

You can use for tab to loop through integer values by one.

<ad:for from="1" to="10" index="i">#i#: #customers[i].name#</ad:for>

Set tag allows you to set values based on other expressions:
<Ad: Set Name = "Var" value = "# someexpression #"/>
After set statement is executed you can use VaR as if it was a local variable.
It might be useful when accessing complex object values.
Instead of writing:
# Customers [I]. Address. firstname # customers [I]. Address. lastname # customers [I]. Address. address1 #
You can do: Lt; AD: Set Name = "add" value = "# customers [I]. address # "/> # Add. firstname ## add. lastname ## add. address1 #
It's especially useful with createtypereference function (see above)

Custom templates:
You can also create your own templates inside of template file that you can call. You do that using template Tag:

<ad:template name="ShowCustomer">#customer.lastname#, #customer.firstname# </ad:template><ad:showcustomer customer="#cust#" />

You can pass any attributes to the template, and you can use those inside of the template. the template can also access all variables that are defined outside of the template. when calling template you have to put trailing slash at the end, or put closing tag:
<Ad: showcustomer/>
<Ad: showcustomer> </AD: showcustomer>

The template also encoded ed special variable: innertext that is the content of executing the inner elements of calling template.

<ad:template name="bold"><b>#innerText#</b></ad:template><ad:bold>#cust.lastname#, #cust.firstname#</ad:bold>

The output will be: <B> Jackson, Tom </B> (if customer is Tom Jackson)

You can also nest those:

<ad:template name="italic">#innerText#</ad:template><ad:bold><ad:italic>This will be bold and italic</ad:italic></ad:bold>

You can also invoke templates based on the name using apply Tag:

<ad:apply template="#usetemplate#">this is content</ad:apply>

If usetemplate is "bold" then "bold" template will be called.

Templates Can be nested inside other template:

<ad:template name="doit"><ad:template name="colorme"><font color=#color#>#innerText#</font></ad:template><ad:colorme color="blue">colorize me</ad:colorme></ad:template>

Colorme template can only be used within doit template.
Templates can also be added programmatically:

TemplateManager mngr = ...;mngr.AddTemplate(Template.FromString("bold", "<b>#innerText#</b>"));

Now bold template can be used anywhere within processing.

Version 2.0 adds ability to create custom tags in C # (or any. Net Language) that can extend the templatemanager with additional functionality. Together with the sources is Example 2 which between des 2 custom tagsEmailFor sending email andBase64For base64 encoding content.
Once those tags are registered with templatemanger you can call them like:
<Ad: email from = "" to = "" subject = "hello" Server = ""> hello # customer. firstname # customer. lastname # </AD: email>

Version 2 also added itemplatehandler interface for better interaction with template execution. you can than set templatemanager's handler property to a handler, and this handler will be called before and after manager is done processing the template. this handler is also availableThisObject, and you can access any property or call methods of the handler from within the template. Example 2 between des "myhandler. cs" as an example on how to use it.

------------------------- Here is a sample based on order confirmation.

class Order{string firstname, lastname, address1, city, state, zip, country;public string Address1{get { return this.address1; }}public string City{get { return; }}public string Country{get { return; }}public string Firstname{get { return this.firstname; }}public string Lastname{get { return this.lastname; }}public string State{get { return this.state; }}public string Zip{get { return; }}}Order order = GetOrder();TemplateManager mngr = TemplateManager.FromFile("");mngr.SetValue("order", order);System.IO.StringWriter writer = new System.IO.StringWriter();mngr.Process(writer);string emailBody = writer.ToString();


<ad:showitem>#item.sku# -<br><ad:if test="#equals(item.qty, 1)#">Price: #format(item.price, "C")#<br><ad:else>You bought #item.qty# items for #format(item.price, "C")# (total: #format(, "C")#)</ad:if></ad:showitem>#order.firstname# #order.lastname#<br>#order.address1#<br><ad:if test="#isnotempty(order.address2)#">#order.address2#<br></ad:if>, #order.state#<br><table><ad:foreach collection="#order.orderitems#" var="orderitem" index="i"><tr><td>#i#.</td><td bgcolor="#iif(isodd(i), "##DEDEDE", "white")#"><ad:showitem item="#orderitem#" /></td></tr></ad:foreach></table>Shipping: #format(order.shipping, "C")#<br>Taxes: #format(, "C")#<br>Order Total: #format(, "C")#<br>

Description of
First showitem template is defined which shows a single line item of the order. item is passed as attribute to showitem.
Then address is shown. note how if is used to conditionally display second line of address with ending <br> tag.
Then each line item of order is looped through using AD: forech tag. IIF function is used to color everyother line with # dedede color.

Example #2 for constructing complex SQL queries:

string[] cols = new string[]{"id", "name", "email"};TemplateManager mngr = TemplateManager.FromFile(file);mngr.SetValue("colums", cols);mngr.SetValue("tablename", "customer");string query = mngr.Process();

And the template file is:

select #toList(columns, ",")# from #tablename#

Example 1 Project has 2 Sample templates that are used to process the same data. First it outputs it as a C # class to the screen, then it uses HTML template to Create HTML file.
There are more examples in the specified des source code distribution. Look at directories: Example 1, Example 2 and tester.
If you have any questions, you can use adertemplates forums at

  • Download source code (700kb)-includes full source code for the library, example program and simple GUI for testing templates. solution is for vs2005 beta 2.
  • Download Library only (26kb)-except des only DLL for library. Works with. NET 2.0 only.
  • Download source code for. NET Framework 1.1 (268kb)-supported des full source code for the library, and small example program. To see more examples download Framework 2.0 version.
    Solution is for vs2003

    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: 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.