Etiquetas de transformação
4D provides a set of transformation tags which allow you to insert references to 4D variables or expressions, or to perform different types of processing within a source text, referred to as a "template". These tags are interpreted when the source text is executed and generate an output text.
This principle is used in particular by the 4D Web server to build web template pages.
These tags are generally to be inserted as HTML type comments (<!--#Tag Contents-->
) but an xml-compliant alternative syntax is available for some of them.
É possível misturar vários tipos de etiquetas. Por exemplo, a seguinte estrutura HTML é inteiramente viável:
<HTML>
<BODY>
<!--#4DSCRIPT/PRE_PROCESS--> (Method call)
<!--#4DIF (myvar=1)--> (If condition)
<!--#4DINCLUDE banner1.html--> (Subpage insertion)
<!--#4DENDIF--> (End if)
<!--#4DIF (mtvar=2)-->
<!--#4DINCLUDE banner2.html-->
<!--#4DENDIF-->
<!--#4DLOOP [TABLE]--> (Loop on the current selection)
<!--#4DIF ([TABLE]ValNum>10)--> (If [TABLE]ValNum>10)
<!--#4DINCLUDE subpage.html--> (Subpage insertion)
<!--#4DELSE--> (Else)
<B>Value: <!--#4DTEXT [TABLE]ValNum--></B><br/> (Field display)
<!--#4DENDIF-->
<!--#4DENDLOOP--> ](End for)
</BODY>
</HTML>
Princípios de utilização das etiquetas
Parsing
Parsing the contents of a template source is done in two contexts:
-
Using the
PROCESS 4D TAGS
command; this command accepts a template as input, as well as optional parameters and returns a text resulting from the processing. -
Using 4D's integrated HTTP server: template pages sent by means of the
WEB SEND FILE
(.htm, .html, .shtm, .shtml),WEB SEND BLOB
(text/html type BLOB),WEB SEND TEXT
commands, or called using URLs. Nesse último caso, por motivos de otimização, as páginas sufixadas com ".htm" e ".html" NÃO são analisadas. Para analisar páginas HTML nesse caso, você deve adicionar o sufixo ".shtm" ou ".shtml" (por exemplo, http://www.server.com/dir/page.shtm).
Processamento recursivo
4D tags are interpreted recursively: 4D always attempts to reinterpret the result of a transformation and, if a new transformation has taken place, an additional interpretation is performed, and so on until the product obtained no longer requires any further transformation. Por exemplo, dada a seguinte instrução:
<!--#4DHTML [Mail]Letter_type-->
If the [Mail]Letter_type
text field itself contains a tag, for example <!--#4DSCRIPT/m_Gender-->
, this tag will be evaluated recursively after the interpretation of the 4DHTML tag.
This powerful principle meets most needs related to text transformation. Note, however, that in some cases this can also allow malicious code to be inserted in the web context, which can be avoided.
Identificadores com tokens
To ensure the correct evaluation of expressions processed via tags, regardless of the language or 4D version, it's recommended to use the tokenized syntax for elements whose name may vary over versions (commands, tables, fields, constants). For example, to insert the Current time
command, enter Current time:C178
.
Utilizar o "." como separador decimal
4D always uses the period character (.) as a decimal separator when evaluating a numerical expression using a 4D tag 4DTEXT
, 4DHTML
, and 4DEVAL
. Os parâmetros regionais são ignorados. This feature facilitates code maintenance and compatibility between 4D languages and versions.
4DBASE
Sintaxe: <!--#4DBASE folderPath-->
The <!--#4DBASE -->
tag designates the working directory to be used by the <!--#4DINCLUDE-->
tag.
When it is called in a Web page, the <!--#4DBASE -->
tag modifies all subsequent <!--#4DINCLUDE-->
calls on this page, until the next <!--........-->
, if any. If the<!--#4DBASE -->
folder is modified from within an included file, it retrieves its original value from the parent file.
The folderPath parameter must contain a pathname relative to the current page and it must end with a slash (/
). A pasta designada deve estar localizada dentro da pasta Web.
Pass the "WEBFOLDER" keyword to restore the default path (relative to the page).
O código seguinte, que deve especificar um caminho relativo para cada chamada:
<!--#4DINCLUDE subpage.html-->
<!--#4DINCLUDE folder/subpage1.html-->
<!--#4DINCLUDE folder/subpage2.html-->
<!--#4DINCLUDE folder/subpage3.html-->
<!--#4DINCLUDE ../folder/subpage.html-->
... é equivalente a:
<!--#4DINCLUDE subpage.html-->
<!--#4DBASE folder/-->
<!--#4DINCLUDE subpage1.html-->
<!--#4DINCLUDE subpage2.html-->
<!--#4DINCLUDE subpage3.html-->
<!--#4DBASE ../folder/-->
<!--#4DINCLUDE subpage.html-->
<!--#4DBASE WEBFOLDER-->
Por exemplo, para definir um directório para a página inicial:
/* Index.html */
<!--#4DIF LangFR=True-->
<!--#4DBASE FR/-->
<!--#4DELSE-->
<!--#4DBASE US/-->
<!--#4DENDIF-->
<!--#4DINCLUDE head.html-->
<!--#4DINCLUDE body.html-->
<!--#4DINCLUDE footer.html-->
In the "head.html" file, the current folder is modified through <!--#4DBASE -->
, without this changing its value in "Index.html":
/* Head.htm */
/* o directório de trabalho aqui é relativo ao ficheiro incluído (FR/ ou US/) */
<!--#4DBASE Styles/-->
<!--#4DINCLUDE main.css-->
<!--#4DINCLUDE product.css-->
<!--#4DBASE Scripts/-->
<!--#4DINCLUDE main.js-->
<!--#4DINCLUDE product.js-->
4DCODE
Sintaxe: <!--#4DCODE codeLines-->
La balise 4DCODE
permet d'insérer un bloc de code 4D de plusieurs lignes dans un template.
When a <!--#4DCODE
sequence is detected that is followed by a space, a CR or a LF character, 4D interprets all the lines of code up to the next -->
sequence. The code block itself can contain carriage returns, line feeds, or both; it will be interpreted sequentially by 4D.
Por exemplo, pode escrever num modelo:
<!--#4DCODE
//PARAMETERS initialization C_OBJECT:C1216($graphParameters)
OB SET:C1220($graphParameters;"graphType";1)
$graphType:=1
//...your code here If(OB Is defined:C1231($graphParameters;"graphType"))
$graphType:=OB GET:C1224($graphParameters;"graphType")
If($graphType=7)
$nbSeries:=1
If($nbValues>8)
DELETE FROM ARRAY:C228 ($yValuesArrPtr{1}->;9;100000)
$nbValues:=8
End if
End if End if
-->
Eis as características da etiqueta 4DCODE:
- The
TRACE
command is supported and activates the 4D debugger, thus allowing you to debug your template code. - Any error will display the standard error dialog that lets the user stop code execution or enter debugging mode.
- The text in between
<!--#4DCODE
and-->
is split into lines accepting any line-ending convention (cr, lf, or crlf). - The text is tokenized within the context of the database that called
PROCESS 4D TAGS
. Isto é importante para o reconhecimento dos métodos de projeto, por exemplo. The Available through tags and 4D URLs (4DACTION ...) method property is not taken into account. - Even if the text always uses English-US, it is recommended to use the token syntax (:Cxxx) for command and constant names to protect against potential problems due to commands or constants being renamed from one version of 4D to another.
The fact that 4DCODE tags can call any of the 4D language commands or project methods could be seen as a security issue, especially when the database is available through HTTP. However, since it executes server-side code called from your own template files, the tag itself does not represent a security issue. In this context, as for any Web server, security is mainly handled at the level of remote accesses to server files.
4DEACH e 4DENDEACH
Sintaxe: <!--#4DEACH variável na expressão-->
<!--#4DENDEACH-->
The <!--#4DEACH-->
comment allows iterating a specified item over all values of the expression. The item is set to a variable whose type depends on the expression type.
The <!--#4DEACH-->
comment can iterate through three expression types:
- collections: loop through each element of the collection,
- seleções de entidade: loop através de cada entidade,
- objects: loop through each object property.
The number of iterations is evaluated at startup and will not change during the processing. Adicionar ou remover itens durante o loop não é recomendado porque resulta em iterações faltantes ou redundantes.
<!--#4DEACH item in collection-->
This syntax iterates on each item of the collection. The code portion located between <!--#4DEACH -->
and <!--#4DENDEACH-->
is repeated for each collection element.
The item parameter is a variable of the same type as the collection elements.
The collection must contain only elements of the same type, otherwise an error is returned as soon as the item variable is assigned the first mismatched value type.
The number of loops is based on the number of elements of the collection. At each iteration, the item variable is automatically filled with the matching element of the collection. Os pontos abaixo devem ser considerados:
- If the item variable is of the object type or collection type (i.e. if expression is a collection of objects or of collections), modifying this variable will automatically modify the matching element of the collection (because objects and collections share the same references). Se a variável for de tipo escalar, só se modificará a variável.
- The item variable gets the same type as the first collection element. If any collection element is not of the same type as the variable, an error is generated and the loop stops.
- If the collection contains elements with a Null value, an error is generated if the item variable type does not support Null values (such as longint variables).
Exemplo com uma coleção de valores escalares
getNames devolve uma coleção de cadeias de caracteres. The method has been declared as "available through 4D tags and URLs".
<table class="table">
<tr><th>Name</th></tr>
<!--#4DEACH $name in getNames-->
<tr>
<td><!--#4DTEXT $name--></td>
</tr>
<!--#4DENDEACH-->
</table>
Exemplo com uma coleção de objetos
getSalesPersons devolve uma coleção de objetos.
<table class="table">
<!--#4DCODE
$salePersons:=getSalesPersons
-->
<tr><th>ID</th><th>Firstname</th><th>Lastname</th></tr>
<!--#4DEACH $salesPerson in $salePersons-->
<tr>
<td><!--#4DTEXT $salesPerson.ID--></td>
<td><!--#4DTEXT $salesPerson.firstname--></td>
<td><!--#4DTEXT $salesPerson.lastname--></td>
</tr>
<!--#4DENDEACH-->
</table>
<!--#4DEACH entity in entitySelection-->
Essa sintaxe itera em cada entidade da seleção de entidades. The code portion located between <!--#4DEACH -->
and <!--#4DENDEACH-->
is repeated for each entity of the entity selection.
The entity parameter is an object variable of the entity selection class.
O número de loops é baseado no número de entidades da seleção de entidades. At each iteration, the entity object variable is automatically filled with the matching entity of the entity selection.
Exemplo com uma tabela html
<table class="table">
<tr><th>ID</th><th>Name</th><th>Total purchase</th></tr>
<!--#4DEACH $customer in ds. Customers.all()-->
<tr>
<td><!--#4DTEXT $customer.ID--></td>
<td><!--#4DTEXT $customer.name--></td>
<td><center><!--#4DTEXT String($customer.totalPurchase;"$###,##0")--></center></td>
</tr>
<!--#4DENDEACH-->
</table>
Exemplo com PROCESS 4D TAGS
var customers : cs.CustomersSelection
var $input; $output : Text
customers:=ds.Customers.all()
$input:="<!--#4DEACH $cust in customers-->"
$input:=$input+"<!--#4DTEXT $cust.name -->"+Char(Carriage return)
$input:=$input+"<!--#4DENDEACH-->"
PROCESS 4D TAGS($input; $output)
TEXT TO DOCUMENT("customers.txt"; $output)
<!--#4DEACH property in object-->
This syntax iterates on each property of the object. The code portion located between <!--#4DEACH -->
and <!--#4DENDEACH-->
is repeated for each property of the object.
The property parameter is a text variable automatically filled with the name of the currently processed property.
As propriedades do objeto são processadas de acordo com sua ordem de criação. Durante o loop, propriedades podem ser adicionadas ou eliminadas no objeto, sem modificar o número de loops que permanecerão no número original de propriedades do objeto.
Exemplo com as propriedades de um objeto
getGamers is a project method that returns an object like ("Mary"; 10; "Ann"; 20; "John"; 40) to figure gamer scores.
<table class="table">
<!--#4DCODE
$gamers:=getGamers
-->
<tr><th>Gamers</th><th>Scores</th></tr>
<!--#4DEACH $key in $gamers-->
<tr>
<td ><!--#4DTEXT $key--></td>
<td ><!--#4DTEXT $gamers[$key]--></td>
</tr>
<!--#4DENDEACH-->
</table>
4DEVAL
Sintaxe: <!--#4DEVAL expression-->
Sintaxe alternativa: $4DEVAL(expressão)
A etiqueta 4DEVAL
permite que você avalie uma variável ou expressão 4D. Like the 4DHTML
tag, 4DEVAL
does not escape HTML characters when returning text. However, unlike 4DHTML
or 4DTEXT
, 4DEVAL
allows you to execute any valid 4D statement, including assignments and expressions that do not return any value.
Por exemplo, é possível executar:
$input:="<!--#4DEVAL a:=42-->" //atribuição
$input:=$input+"<!--#4DEVAL a+1-->" //cálculo
PROCESS 4D TAGS($input;$output)
//$output = "43"
In case of an error during interpretation, the text inserted will be in the form: <!--#4DEVAL expr-->: ## error # error code
.
For security reasons, it is recommended to use the
4DTEXT
tag when processing data introduced from outside the application, in order to prevent the insertion of malicious code.
4DHTML
Sintaxe: <!--#4DHTML expression-->
Sintaxe alternativa: $4DHTML(expressão)
Just like the 4DTEXT
tag, this tag lets you assess a 4D variable or expression that returns a value, and insert it as an HTML expression. This value is inserted as simple text, special HTML characters such as ">" are automatically escaped.
For example, here are the processing results of the 4D text variable myvar with the available tags:
Valor myvar | Etiquetas | Resultados |
---|---|---|
myvar:="<B>" | <!--#4DTEXT myvar--> | <B> |
myvar:="<B>" | <!--#4DHTML myvar--> | <B> |
In case of an interpretation error, the inserted text will be <!--#4DHTML myvar--> : ## error # error code
.
For security reasons, it is recommended to use the
4DTEXT
tag when processing data introduced from outside the application, in order to prevent the insertion of malicious code.
4DIF, 4DELSE, 4DELSEIF e 4DENDIF
Sintaxe: <!--#4DIF expression-->
{<!--#4DELSEIF expression2-->...<!--#4DELSEIF expressionN-->
} {<!--#4DELSE-->
} <!--#4DENDIF-->
Used with the <!--#4DELSEIF-->
(optional), <!--#4DELSE-->
(optional) and <!--#4DENDIF-->
comments, the <!--#4DIF expression-->
comment offers the possibility to execute portions of code conditionally.
The expression parameter can contain any valid 4D expression returning a Boolean value. It must be indicated within parenthesis and comply with the 4D syntax rules.
In case of an interpretation error, the text "<!--#4DIF expression-->
: A Boolean expression was expected" is inserted instead of the contents located between <!--#4DIF -->
and <!--#4DENDIF-->
. Likewise, if there are not as many <!--#4DENDIF-->
as <!--#4DIF -->
, the text "<!--#4DIF expression-->
: 4DENDIF expected" is inserted instead of the contents located between <!--#4DIF -->
and <!--#4DENDIF-->
.
In case of an interpretation error, the text "<!--#4DIF expression-->
: A Boolean expression was expected" is inserted instead of the contents located between <!--#4DIF -->
and <!--#4DENDIF-->
. Likewise, if there are not as many <!--#4DENDIF-->
as <!--#4DIF -->
, the text "<!--#4DIF expression-->
: 4DENDIF expected" is inserted instead of the contents located between <!--#4DIF -->
and <!--#4DENDIF-->
.
Using the <!--#4DELSEIF-->
tag, you can test an unlimited number of conditions. Only the code that follows the first condition evaluated as True
is executed. If no conditions are true, no statement is executed (if there is no final <!--#4DELSE-->
). You can use a <!--#4DELSE-->
tag after the last <!--#4DELSEIF-->
. If all the conditions are false, the statements following the <!--#4DELSE-->
are executed.
Os dois códigos seguintes são equivalentes.
Código utilizando apenas 4DELSE:
<!--#4DIF Condition1-->
/* A condição1 é verdadeira*/
<!--#4DELSE-->
<!--#4DIF Condition2-->
/* A condição2 é verdadeira*/
<!--#4DELSE-->
<!--#4DIF Condition3-->
/* A condição3 é verdadeira */
<!--#4DELSE-->
/*Nenhuma das condições é verdadeira*/
<!--#4DENDIF-->
<!--#4DENDIF-->
<!--#4DENDIF-->
Código semelhante usando a tag 4DELSEIF
:
<!--#4DIF Condition1-->
/* A condição1 é verdadeira*/
<!--#4DELSEIF Condition2-->
/* A condição2 é verdadeira*/
<!--#4DELSEIF Condition3-->
/* A condição3 é verdadeira */
<!--#4DELSE-->
/* Nenhuma das condições é verdadeira*/
<!--#4DENDIF-->
This example of code inserted in a static HTML page displays a different label according the vname#""
expression result:
<BODY>
...
<!--#4DIF (vname#"")-->
Names starting with <!--#4DTEXT vname-->.
<!--#4DELSE-->
No name has been found.
<!--#4DENDIF-->
...
</BODY>
Este exemplo insere páginas diferentes dependendo de qual usuário está conectado:
<!--#4DIF LoggedIn=False-->
<!--#4DINCLUDE Login.htm -->
<!--#4DELSEIF User="Admin" -->
<!--#4DINCLUDE AdminPanel.htm -->
<!--#4DELSEIF User="Manager" -->
<!--#4DINCLUDE SalesDashboard.htm -->
<!--#4DELSE-->
<!--#4DINCLUDE ItemList.htm -->
<!--#4DENDIF-->