ExperShop - DynHtml


Home Contents

Please email any bug reports, comments or suggestions to ExperLog's Online Support


Overview

DynHtml is a technology dedicated to include database and other dynamic content in HTML pages.

DynHtml pages are expanded on-the-fly by ExperSHOP, and database query results are included in the HTML text (as well as other possible dynamic information, such as HTTP parameters for example).

DynHtml templates are ascii files that mix HTML with specific DynHtml tags: they are expanded at run time, to display dynamic information.

How to write a DynHtml template

Here's an example of a DynHtml template:

  <html><body>
  <b>Customer List</b><p>

  $DefineSql GetCustomers SELECT FirstName, LastName FROM Customer

  $IfPresent AgeMin
   $AppendSql GetCustomers WHERE Age>AgeMin
  $Endif

  $ExecSql GetCustomers

  $IfNoResult GetCustomers
   There's no Customer.
  $Else

   $LoopOnResults GetCustomers cust
    Customer Name: $cust:FirstName$, $cust:LastName$<br>
   $EndLoop

  $Endif

  </body></html>

  

The values of FirstName and LastName returned in the query results will appear in the browser in place of $cust:FirstName$ and $cust:LastName$;
The end user may see:

Customer List

Customer Name: Paul, Smith
Customer Name: Bill, Jones

Note the "$IfPresent... $Endif" statement: if the DynHtml template is invoked with an HTTP parameter named "AgeMin", a WHERE clause is appended to the SQL query.

How to expand a DynHtml page

DynHtml pages are expanded by the ExperSHOP servlets: the user has nothing to do to expand the pages.

DynHtml statements

  $#
  $Action
  $Add
  $Append
  $AppendSql
  $AppendSql2
  $Assign
  $Case
  $CheckNumber
  $ClearError
  $Cookie
  $Debug
  $Default
  $Defvar
  $Div
  $Else (see If... statements)
  $EndCase
  $Endif (see If... statements)
  $EndLoop (see LoopOnEnum, LoopOnFiles, LoopOnResults)
  $EndSwitch
  $ExecSql
  $Exit
  $ExitLoop
  $ExpandFile
  $ExpandSql
  $Forward
  $FetchProduct
  $If
  $IfEe
  $IfEqual
  $IfError
  $IfFilePresent
  $IfGe
  $IfGt
  $IfLe
  $IfLt
  $IfNoResult
  $IfPresent
  $Include
  $Invoke
  $LoopOnEnum
  $LoopOnFiles
  $LoopOnResults
  $Mul
  $NewObject
  $SetCookie
  $Sub
  $Switch
  $System
  

Variables and parameters

Variables, parameters, column values in query result sets, etc... are defined by a variable name; to display a value that corresponds to a variable name, just surround it with "$" characters: $variable-name$

Some formatting information can be specified, for example to format numeric values: The format should be enclosed in parentheses, just after the "$" character that delimits the variable (for example, $(.00)variable-name$ will display the variable's value with 2 decimals).

Numeric formats:

Any format supported by the java.text.DecimalFormat class.
For example, ".00" will cause "20.123" to be displayed as "20.12" and "20.1" as "20.10".
The format should be enclosed in parentheses, just after the "$" character that delimits the value.
Examples:

  $(.00)Price$
  $(##.##)TotalPrice$
  

Note that numeric formats can have unspecified effects when rounding numbers to integer values: particularly, (0) or (00) when applied to something else than integers.

If this is what you want to do, first round the values by using (Round), (Ceil) or (Floor) formats.
(Round) rounds a number to the closest integer value.
(Ceil) rounds a number to the smallest integer value that is greater than its argument.
(Ceil) rounds a number to the largest integer value that is smaller than its argument.

String formats:

String.sub - Substring. For example, $(String.sub5,8)astring$ will return characters between the 5th position (included) and the 8th position (excluded), and $(String.sub5)astring$ will return all the characters after the 5th position (included). Note that the 1st position is 0, not 1.
String.length - String length (integer).
String.indexof:substring - Substring lookup. The position of the 1st character of the 1st occurrence of substring in the target string is returned (starting at 0). "substring" is a variable name : if a constant is required, add a "%" character at the beginning (for example, $(String.indexof:test)mystring$ looks for the value of the "test" variable, and $(String.indexof:%test)mystring$ looks for the string "test").
String.padl - Pad a string to a given length, adding blank characters to the left. For example, if $helloworld$ is "Hello World", $(String.padl20)helloworld$ will return "         Hello World".
String.padr - Pad a string to a given length, adding blank characters to the right. For example, if $helloworld$ is "Hello World", $(String.padr20)helloworld$ will return "Hello World         ".
String.padc - Pad a string to a given length, and center it. For example, if $helloworld$ is "Hello World", $(String.padc20)helloworld$ will return "    Hello World     ".

Date formats:
See the "working with dates" document.

Other formats:

Upper - Convert to upper case (example: $(Upper)name$)
Lower - Convert to lower case (example: $(Lower)name$)
UcFirst - Convert 1st character to upper case (example: $(UcFirst)name$)
UrlEncode - URL-encode a value (example: $(UrlEncode)name$)
HtmlEncode - Encode a string to escape special characters in HTML (for example, for values in "hidden" tags). Escapes ", &, < and > respectively as &quot;, &amp;, &lt; and &gt;.
(example: $(HtmlEncode)name$)
JsEncode - Encode a string to escape special characters in Javascript string values. Escapes " and ' respectively as \" and \'.
(example: $(JsEncode)name$)
XmlEncode - Encode a string to escape special characters in XML attribute or element values.
(example: $(XmlEncode)name$)
SqlEncode - Encode for use in an SQL request. If the word is used as is, the encoding will be used with the main datasource of the application.
(example: $(SqlEncode)name$)
It is possible to set the datasource name for the encoding: $(SqlEncode.[datasource_name])name$
(example: $(SqlEncode.Oracle)name$)
RemoveHtmlTags - Remove HTML tags (example: $(RemoveHtmlTags)name$)
QuoteMessage - Format like quoted (inline) messages in email answers ("> " at the beginning of each line). Example: $(QuoteMessage)msg$

DynHtml predefined variables

$COOKIE$

The ExperShop session information, to be included in ExperSHOP URLs (in HTTP links, using the <A HREF=...> tag).
Example:
<A HREF="com.expershop.lite.ExperSHOP?$COOKIE$&Page=NextPage.tmpl"> Go to next page</A.>

See also: $Cookie statement, for URLs invoked as HTML form actions.

$\$

Displays a "$" character.
This escape sequence is sometimes necessary: for example, "Item price: $10" will be displayed as is.
But "Item price: $10, plus $2 shipping cost" will not, because ExperSHOP will try to expand a variable called "10, plus " (the text enclosed between the two "$" characters).
In that case, you have to use the "$\$" variable: "Item price: $\$10, plus $\$2 shipping cost" will work perfectly.

Data sets and data objects

A data object is equivalent to a database tuple, with attributes equivalent to database columns.

A data set is a set of data objects: for example, the result of a database query, or the shopping cart seen as a set of items.
If is possible to loop on a data set, using the $LoopOnResults...$EndLoop statement; In the loop, you can access the attributes of the current data object.

There are two kinds of data sets: the expershop built-in data sets (like the Shopping Cart or the Shop's configuration file), and the run-time data sets (transient data sets, like database query results or string enumerations).

For example, ExperShop provides a built-in data object called ShoppingCart, that gives access to the shopping cart: this object has an attribute called TotalPrice, the total amount of the shopping cart: you can display it in a DynHtml page as $ShoppingCart:TotalPrice$.

The Shopping Cart is also a data set: you can loop on cart items, then display each item's characteristics (each item being a data object).
In a $LoopOnResults ShoppingCart item ... $EndLoop loop, you can for instance access the item's quantity by specifying $item:Qty$.

Of course, SQL queries are data sets, as soon as they have been executed:
For example, the $ExecSql MyQuery [MyBase] statement creates a data set called "MyQuery" with the "MyBase" database, you can loop on. The "MyBase" database is defined in the configuration file of the application.

Defining variables and parameters

A variable is a name/value association.
To define a variable, use the $DefVar statement.
Example: $DefVar ndays 31

A parameter is a variable that will be considered an HTTP parameter in the current page: it will be passed to actions if $Action is used. (note: parameters won't be transmitted furter if the current page is submitted as a form.
To define a parameter, use the $Assign statement.
Example: $Assign name John

To append text to a previously defined variable or parameter, use the $Append statement.
To append a blank character, enclose it in double quotes.
Example:
$Append name " "
$Append name Smith

A variable may be computed :
Example:

$DefVar day (24 * 60 * 60)

Enumerations

An enumeration is a list of values separated by commas, or a continuous series of integers, or both; for example, you can define enumerations like this:
$DefVar months Jan,Feb,Mar,Apr,May,Jun,Jul,Sep,Oct,Nov,Dec
$DefVar weekdays 1->7
The first one lists the months, the 2nd is equivalent to 1,2,3,4,5,6,7.
It is valid to combine the 2 constructs: for example,
$DefVar intervals 1->5,10->20

It is possible to loop on enumeration values, using the $LoopOnEnum ... $EndLoop statement; for example:

  $LoopOnEnum months mm
  Current Month is: $mm:value$
  $EndLoop

  $LoopOnEnum weekdays d
  Current day is: $d:value$
  $EndLoop
  
In fact, an enumeration value can be considered as a data set, with tuples that contain only one column, called "value" (the reason for mm:value in the loop above).

Errors

Some statements, like $ExecSql (execute an SQL query) or $Action (execute an action), can result in runtime errors.

It is possible to handle runtime errors using the $IfError...$Endif statement, and/or to clear errors using the $ClearError statement.

Passing client session information in HTML forms

The $Cookie statement passes client session information as "HIDDEN" tags in HTML forms.
$Cookie is expanded into a set of "<INPUT TYPE=HIDDEN ...>" tags, to be submitted in an HTML form to pass the ExperSHOP client session information.

Example (most HTML forms should begin as follows in a DynHtml template):

  <FORM METHOD=POST ACTION="com.expershop.lite.ExperSHOP">
  $Cookie
  

Setting "cookie" client session information

$Cookie allows to access any information stored in the client session information: for example, $Cookie:CustId$ is the customer ID when a customer is logged in.

Note that ExperShop does not use REAL cookies: in this document, "cookie" refers to session information stored on the server and associated to a session id.

It is possible to store variables in the "cookie" information:

  • By passing HTTP parameters whose name ends with "_" (like "custominfo_") through HTTP links or forms: any parameter whose name ends with "_" will be kept in the "cookie" information, during the whole session's lifetime.
  • By calling $SetCookie.
    For example, $SetCookie userinfo Hello World will define a new "cookie" session variable called "userinfo"; to retrieve its value, use $Cookie:userinfo$

SQL Requests

It is possible to define SQL requests, execute them, and loop on query results to display the tuples.

Define SQL request

  $DefineSql requestName sql-statement
  

Append text to SQL request
  $AppendSql requestName text
  $AppendSql2 requestName text
  
$AppendSql and $AppendSql2 can be used to append text to an SQL request. $AppendSql2 immediately evaluates variables that can be resolved (expands the query string), $AppendSql does not (so there may be variables in the request, that will be resolved by $ExecSql).
$AppendSql can be used in conjunction with "If... Else" statements, to complete an SQL request text.
Note: If text begins with "AND" or "OR", the AND or OR string will be removed if text is the first condition of a WHERE clause.
For example, appending "AND Price>10" to a query equal to "SELECT * FROM Items WHERE" will result in "SELECT * FROM Items WHERE Price>10".
Then, appending "AND Price<100" will result in "SELECT * FROM Items WHERE Price>10 AND Price<100".

Execute SQL

  $ExecSql requestName [baseName]
  
Evaluates all variables in the request string, then executes it.
The name of the database is not required when it is the database defined in the configuration file of the application, else, the database must be defined by a datasource in the configuration file of the application.


Loop on query results

  $LoopOnResults requestName tupleName [i j]
  ...
  $EndLoop
  
It is possible to add to the tuple name, the boundaries of the request, to loop from i to j. Attention, this option does not guaranty the order of the elements coming from the database.
exemple :
  $LoopOnResults MyREQ myTuple 11 20
  ...
  $EndLoop
  

Display a column value (in a loop)

$tupleName:name$ The value, tupleName is the tuple name defined by the LoopOnResults statement, and name is the column name.

Handle no result case

  $IfNoResult requestName
  ...
  $Else
  ...
  $Endif
  

Handle error
  $IfError
  ...
  $Else
  ...
  $Endif
  

Retrieve an SQL request into a variable

  $ExpandSql varname requestName
  

Actions

You can execute an ExperSHOP Action from a DynHtml template, using the $Action statement (to learn more about ExperSHOP Actions, see the DynHtml actions web page).

Syntax: $Action action-class [action-parameter]
action-parameter is optional (few actions receive parameters this way: generally, parameters are passed to actions using HTTP parameters).
action-class is the action class name.

Example: empty the shopping cart

  $Action com.expershop.actions.ESEmptyCart
  

Check a variable's presence

  $IfPresent varname
  ...
  $Else
  ...
  $Endif
  
Examples:
$IfPresent FirstName
$IfPresent customer:FirstName (in a loop)

Check a file's presence

  $IfPresent filename
  ...
  $Else
  ...
  $Endif
  
Examples:
$IfFilePresent localFile.txt (in the current directory)
$IfFilePresent /tmp/afile.txt (absolute path)
$IfFilePresent f:FileName (in a loop)

Accessing the content of a directory

  $LoopOnFiles directory file
   Name: $file:name$, Extension: $file:ext$,
	 Date: $(DateFormat.dd/MM/yyyy)file:lastmodified$,
   IsFile: $file:isfile$ <br>
   ...
  $EndLoop
  
The directory may be relative to ESRootDir, or absolute (for example, if it starts with / on a Unix system).
The "isfile" field is set to 1 for normal files, 0 for others (directories, symlinks...)

Number syntax checking

It is sometimes necessary to check wether a value is a number or not.
$CheckNum performs the check, and raises an error if the value is not a number (the error can then be checked using $IfError ... $Endif, then cleared using $ClearError); Example:
  $DefVar x 2.3
  $CheckNumber $x$
  $IfError
   ERROR: $x$ is not a number<br>
  $Else
   Ok<br>
  $Endif
  $ClearError
  

Basic calculation operators

It is possible to add, substract, multiply or divide numeric values, using $Add, $Sub, $Mul and $Div.
The variable involved must be previously declared; example:
  $DefVar a 1
  $Add a 1
  $DefVar b 2
  $Div a $b$
  
In this example, a=1, then we add 1 (a=2), then divide by the value of b (at the end, a=1).

Compare Values

String equality
  $IfEqual varname value
  ...
  $Else
  ...
  $Endif
  
Examples:
$IfEqual City New-York
$IfEqual FirstName ""
$IfEqual FirstName $Name: $
$IfEqual customer:FirstName John (in a loop)

Number comparisons

$IfEe...$Endif (=), $IfGe...$Endif (>=), $IfGt...$Endif (>), $IfLe...$Endif (<=), $IfLt...$Endif (<)
Examples:

  $IfEe varname 0
  Zero!
  $Endif
  $IfLe varname 10
  $varname$ <= 10
  $Endif
  $IfLt varname $anumber$
  $varname$ < $anumber$
  $Endif
  $IfGe varname 10
  $varname$ >= 10
  $Endif
  $IfGt varname $anumber$
  $varname$ > $anumber$
  $Endif
  

Evaluate and compare expressions

$If allows you to use expressions in the conditional syntax:
  $If ( expression operator expression)
  ...
  $Else
  ...
  $Endif
  
"expression" can be : ($var1$ + 14)*3 + $var2$
"operator" can be a comparison operator, or a logical operator.
Comparison operators are:
 < > <= >= = <> !=
Logical operators are:
  && (logical and)
  || (logical or)
  ! (logical not)
Parentheses can be used to group expressions.
For example, the following construct is valid:
  $If $current$ >= $min$ && ! ($current$ > $max$)
    Current value looks ok.
  $Else
    Current value is out of range.
  $Endif
  

Exit

  $Exit
  
Leave the page immediately.

ExitLoop

  $ExitLoop
  
Leave the current loop immediately.

Switch (Case, EndCase, EndSwitch)

  $Switch var
    $Case val_1
      ...
      ...
    $EndCase

    $Case val_2
      ...
      ...
    $EndCase
    $Default
      ...
      ...
    $EndCase
  $EndSwitch
  
Depends on the expression value, the appropriate case is executed. If no expression matches with the value, it is possible to add a catch-all tag ("$Default").

Display another DynHtml template

  $ExpandFile filepath
  

$ExpandFile is different from $Include: for example, a variable or an SQL query defined in the expanded file will no longer be accessible when back in the original file.
filepath is relative to the directory where the current template is located.

Expand another DynHtml template

  $Include filepath
  

$Include is different from $ExpandFile: for example, a variable or an SQL query defined in the expanded file will be accessible when back in the original file.
filepath is relative to the directory where the current template is located.

Forward the HTTP request to another URL

  $Forward URL
  

URL may be absolute or relative.
$Forward will be ignored if it is not considered relevant (eg. in a $ExpandFile or in a SendMail action...)
Only the original HTTP request will be forwarded (additional parameters like those set using $Assign will be lost).

Execute a system command

  $System command
  

$System executes a system command: the command output, if any, is displayed on the output HTML stream.
For example, to list the files in /tmp on a Unix system:
  <pre>
  $System ls -l /tmp
  </pre>
  

Display debug traces

  $Debug text
  
Displays text on the standard output, for debug purposes.
Examples:
$Debug Hello World!
$Debug LastName = $LastName$

Comments

  $# Comment
  

Fetch a product according to its reference

  $FetchProduct prodId varname
  
Fetch a product from the products database (default: EProduct table), according to the product reference (default: ProdId column). The result is a "data object", named after the specified variable name, with at least 3 fields: ProdId, Name, Price.
That statement is useful to encapsulate products, and avoid extensive use of complex SQL requests in the templates (eg. to compute a product price according to a customer category or a currency...)