Changes between Initial Version and Version 1 of IntroHtmlTemplating


Ignore:
Timestamp:
07/25/06 11:32:45 (8 years ago)
Author:
tstuij
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • IntroHtmlTemplating

    v1 v1  
     1[wiki:IntroNestedComponents Nested Components (:|,) containers and tabbed panes <- back] | [wiki:UcwIntro toc] | [wiki:IntroFormHandling forward -> Advanced form handling]
     2
     3{{{
     4#!html
     5
     6    <h2>Html templating: TAL</h2>
     7    <p>Ucw's template attribute language is loosely based on
     8    <a href='http://www.zope.org/Wikis/DevSite/Projects/ZPT/TAL'>Zope's TAL</a>. It also uses xml to express it's intentions and it uses a few of it operators. Moreover it uses its idea: a way to embed a few programming constructs in xml so that the xml can be parsed back into the language as a design template with some flexibility. Programmers can easily modify the html/xml that designers present to make it fit for code. As can the designers themselves up until a point.</p>
     9    <h5>How it works</h5>
     10    <p>Tal code is confined in .tal files. Those files are called from lisp code to render a page on a component, much like a render method. You can either replace a render method or embed tal files in a render method. You can also embed render methods in tal files, tal files in render methods and you can embed tal files in other tal files. Tal files can harbor control structures, variables and lisp code. When a component is rendered, the  the tal control structures, variables and lisp code in a tal file are evaluated and the specified tal files are transformed into yaclml code, which on it's turn is transformed into xml/html.</p>
     11    <p>An example. (yes you know, it's to be found in the supplied sources. zzz) First add the tal-generator key-value pair to the make-instance of our *ucw-intro-application* in config.lisp and add two entry-point to our dispatcher list. With the stuff added in previous chapters it should look something like this:</p>
     12    <pre>
     13(defparameter *ucw-intro-application*
     14  (make-instance 'cookie-session-application
     15                 :url-prefix "/ucw-intro/"
     16                 :www-roots (list *www-root*)
     17                 :tal-generator (make-instance 'yaclml:file-system-generator
     18                                               :cachep t
     19                                               :root-directories (list *www-root*))
     20                 :dispatchers (list (action-dispatcher)
     21                                    ;; hello world
     22                                    (url-dispatcher "hello-world.ucw"
     23                                      (call 'hello-world))
     24                                    ;; basics
     25                                    (regexp-dispatcher "^(basics.ucw|)$"
     26                                      (call 'basics))
     27                                    (regexp-dispatcher "^(get.ucw|)$"
     28                                      (with-request-params ((cow "moo"))
     29                                          (context.request *context*)
     30                                        (let ((cow (concatenate 'string "mighty " cow)))
     31                                          (call 'basics :cow cow))))
     32                                    ;; containers
     33                                    (regexp-dispatcher "^(containers.ucw|)$"
     34                                      (call 'office))
     35                                    ;; tabbed-pane
     36                                    (regexp-dispatcher "^(pane.ucw|)$"
     37                                      (call 'pane))
     38                                    ;; tal
     39                                    (regexp-dispatcher "^(tal.ucw|)$"
     40                                      (call 'tal-component))
     41                                    (regexp-dispatcher "^(more-tal.ucw|)$"
     42                                      (call 'more-tal)))
     43                 :debug-on-error t))
     44    </pre>
     45    <p>Then we create the first part of tal.lisp:</p>
     46    <pre>
     47(in-package :ucw-intro)
     48    </pre>
     49    <pre>
     50(defcomponent tal-component (template-component)
     51  ((page-name :initarg :page-name :accessor page-name)
     52   (contents :initarg :contents :accessor contents))
     53  ;;  (:entry-point "^(|tal.ucw)$" (:application *ucw-intro-application* :class regexp-dispatcher))
     54  (:default-initargs :template-name "intro.tal" :page-name "Que tal!" :contents "&lt;blink&gt;Qual blink!!!&lt;/blink&gt;"
     55                     :flag t))
     56    </pre>
     57    <p>Observe the :tal-generator bit in the application constructor, which specifies the root directories of the search paths to the tal files. Furthermore we let tal-component inherit from template-component, which adds the :template-name slot to standard component, next to some custom methods that do undercover work. In default-initargs you specify your tal file to render. Let's make that file:</p>
     58    <pre>
     59&lt;html xmlns:tal="http://common-lisp.net/project/bese/tal/core"
     60      tal:in-package=":ucw-intro"&gt;
     61  &lt;head&gt;
     62    &lt;title tal:content="$page-name"&gt;page name goes here&lt;/title&gt;
     63    &lt;link href="sheet.css" rel="stylesheet" type="text/css"/&gt;
     64  &lt;/head&gt;
     65  &lt;body&gt;
     66    &lt;h1 tal:content="(content $component)" tal:escape-html="nil"&gt;content goes here&lt;/h1&gt;
     67    &lt;h1 tal:replace="$contents" tal:escape-html="t"&gt;content goes here&lt;/h1&gt;
     68  &lt;/body&gt;
     69&lt;/html&gt;
     70    </pre>
     71    <p>In the html tag you see the xmlns bits. They are xml name spaces. You can look them up in your browser but they lead to nowhere. But inside lisp they are mapped to different packages where custom defined tags, attributes and parameters reside. In this case :it.bese.yaclml.tal. tal:in-package of course maps to in-package. We for example reach the tal tag and attribute definitions by putting tal: in front of them. They are:</p>
     72    <ul>
     73      <li>tags: tal, lisp, include</li>
     74      <li>attributes: content, replace, when, dolist, in-package</li>
     75    </ul>
     76    <p>When a tag (a tal tag, or a html/xml tag) is parsed, tal checks, from left to right, if the tag and/or any of it's attributes are part of a namespace which begs them to be evaluated by tal. A tag can contain multiple tal attributes and they can be mixed with html/xml attributes. If so tal determines which handler is fit and hands it the tag to be operated upon. (For your understanding, when it concerns an attribute, tal usually eats that attribute, performs the specified operation, and processes the tag again without it.)</p>
     77    <p>To continue the treatment of our example, we examine the attributes content and replace. Content replaces the content of the tag it's a part of (in this case "content goes here") with what's contained in it's variable (the result of "(contents $component). Replace replaces the complete tag with what's in it's variable. They both check for the value of escape-html which doesn't escapes html if the value is nil and which does escape html whenever the value is non-nil. If escape-html isn't supplied it defaults to t.</p>
     78    <p>For completeness: we could also have had our  tal-component class inherit from simple-component and leave out everything except for the contents of the body, and ucw would have added the code around it.</p>
     79    <p>But where are variables defined? How can tal interact with the class it renders? And what about those other tags and attributes? Enter the next section:</p>
     80    <h5>Tal and lisp</h5>
     81    <p>Basically where a tag or an attribute accepts some sort of parameter you usually have a window into lisp. This is the case with lisp, content, replace, when and dolist. The text inside " and " is evaluated, except for tal:lisp which evaluates the text inside its beginning- and end-tag. Variables start with the character $ and are matched against values inside the so-called tal environment. This environments equates to a collection of supplied classes, alists and hash-tables in which tal tries to match the variable. When it does it returns the value. In our example some methods on template-component make sure the component that the tal file is rendered on is included and can be referenced with $component. As you can see you can either use the slot function of contents or you can refer to contents directly by pasting a $ to its front, as you can refer directly to the key of a cons in an a-list or the key in a hash table. Later on you will see ways to extend the tal environment.</p>
     82    <p>Sometimes you want to use a variable, or the output of some lisp code in an ordinary attribute. You can do that by putting "${..your lisp code...}" after the attribute (see the next example). If you for some reason want to splice the contents of a list after an attribute you can replace the $ with a @.</p>
     83    <p>Let's review the rest of the tal tags and attributes. We start of with another example. This time we create a component called more-ucw, two simple classes and a hash table for use with the tal file:</p>
     84    <pre>
     85(defcomponent more-tal (template-component)
     86  ((flag :initarg :flag :accessor flag)
     87   (da-var :initform "da-var from more-tal class" :accessor da-var)
     88   (tal-name :initform "more-wrapper.tal" :accessor tal-name)
     89   (another-var :initform "another-var from more-tal class" :accessor another-var)
     90   (a-href :initform "http://planet.lisp.org" :accessor a-href)
     91   (a-class :initform (make-instance 'in-list) :accessor a-class)
     92   (spliced-href :accessor spliced-href :initform '("http://" "planet." "lisp." "org"))
     93   (my-list :accessor my-list
     94            :initform `((,(make-instance 'in-list)
     95                         ,(make-instance 'another-in-list))
     96                        (((da-var . "da-var from a-list") (another-var . "another-var from a-list")))
     97                        (,(make-instance 'in-list :da-var "da-var from class in another bullet")
     98                         ((da-var . "da-var from another a-list") (another-var . "another-var from another alist")))
     99                        (,*tal-table*))))
     100  ;;  (:entry-point "^(|more-tal.ucw)$" (:application *ucw-intro-application* :class regexp-dispatcher))
     101  (:default-initargs :template-name "more-tal.tal" :flag nil))
     102    </pre>
     103    <pre>
     104(defclass in-list ()
     105  ((da-var :initarg :da-var :initform "da-var from in-list class" :accessor da-var)))
     106    </pre>
     107    <pre>
     108(defclass another-in-list ()
     109  ((another-var :initform "another-var from in-list class" :accessor another-var)))
     110    </pre>
     111    <pre>
     112(defparameter *tal-table* (make-hash-table))
     113    </pre>
     114    <pre>
     115(setf (gethash 'another-var *tal-table*) "another-var from hash")
     116    </pre>
     117    <p>and we make a .tal file called more-tal.tal:</p>
     118    <pre>
     119&lt;html xmlns:tal="http://common-lisp.net/project/bese/tal/core"
     120  xmlns:ucw="http://common-lisp.net/project/ucw/core"
     121  xmlns:param="http://common-lisp.net/project/bese/tal/params"
     122  tal:in-package=":ucw-intro"&gt;
     123  &lt;head&gt;
     124    &lt;title&gt;more tal&lt;/title&gt;
     125    &lt;link href="sheet.css" rel="stylesheet" type="text/css"/&gt;
     126  &lt;/head&gt;
     127  &lt;tal:include tal:name="more-wrapper.tal" param:little-class="(a-class $component)"&gt;
     128    &lt;param:contents&gt;
     129      &lt;div tal:when="$flag" tal:content="$another-var"&gt;
     130        flag is set?
     131      &lt;/div&gt;
     132      &lt;ul&gt;   
     133        &lt;li tal:dolist="$my-list"&gt;
     134          &lt;b tal:content="$da-var"&gt;&lt;/b&gt;&lt;br/&gt;
     135            &lt;tal:tal tal:content="$another-var"&gt;another var&lt;/tal:tal&gt;
     136        &lt;/li&gt;
     137      &lt;/ul&gt;     
     138      &lt;p&gt;&lt;a href="${(a-href $component)}"&gt;attribute insertion&lt;/a&gt;&lt;/p&gt;     
     139      &lt;p&gt;&lt;a href="@{(spliced-href $component)}"&gt;spliced attribute insertion&lt;/a&gt;&lt;/p&gt;
     140      &lt;tal:lisp&gt;
     141        (setf (a-href $component) "http://www.cliki.net")
     142      &lt;/tal:lisp&gt;
     143      &lt;a href="${(a-href $component)}"&gt;new value of href&lt;/a&gt;     
     144    &lt;/param:contents&gt;
     145  &lt;/tal:include&gt;
     146&lt;/html&gt;
     147    </pre>
     148    <p>We leave tal:include and the param: tag and attribute alone for a moment because they need some extra code to explain. We explain the rest first:</p>
     149    <ul>
     150      <li>tal:when - an attribute - which is of course not dissimilar to lisps when. When the value produced by the expression inside the quotation marks equates to nil, attributes after the when tag are not processed. If this means that no tal attribute will supply the tag with content, the whole tag, and it's contents are removed. If a previous attribute already supplied the tag with content through tal:content the tag will not be removed and that content will be shown. If content was previously supplied with tal:replace the tag will be replaced by the content of tal:replace, as this is the behaviour of tal:replace</li>
     151      <li>tal:dolist - an attribute - This is a rather cool and nifty tag. It works not dissimilar to dolist. The code between the quotation marks of dolist should equate to a list of lists containing alists, classes hash-tables or a combination of the former. Dolist iterates over the list of lists. On each iteration the tag dolist is a part of and it's children are evaluated and added to the yaclml tree in the pending tal environment extended with the list which is at that point the list dolist is iterating over. See the initform of the my-list slot of the more-tal component to get a feel for it.</li>
     152      <li>tal:tal - a tag - In the dolist tag tree in more-tal.tal you see tal:tal which is simply a placeholder for attributes that doesn't show up in the html/xml code you want to produce.</li>
     153      <li>the $ AND @ ones after a normal attribute - as discussed earlier these are used when you want to use the result of some lisp code output or a list of some lisp code output respectively after an ordinary attribute.</li>
     154      <li>tal:lisp - a tag - The text enclosed within a tal:lisp tag is processed for side effects. No output is passed back into the tag tree.</li>
     155    </ul>
     156    <p>Now to explain tal:include, which basically does what you expect. Tal:include extends the current tal environment with the parameters that are in the param name-space and that are enclosed in the include tag (so everything with param: in front of it). This environment is passed to the calling tal file which it uses to evaluate it's own tal tags and attributes. You can pass param: tags and param: attributes, which behave differently. Param tags (you may call them whatever you wish) stuff all the evaluated content enclosed in them in a variable. (in the case of our example  this will be in $contents). All the tags enclosed in the include tag are evaluated together with their attributes and the attributes of the param: tag before they are passed to the included tal file. So the content of $contents will be a big (or a little) string. By using attributes on the other hand, you can pass variables that refer to lisp objects. The value of the variable is the value returned by the code enclosed within the quotations that stick to it via the equal sign. The template that tal:include calls can be specified by either a tal:name or tal:name-expression attribute. Tal:name simply maps to the specified tal file. Name-expression evaluates the expression typed inside it's quotation marks, which should equate to a valid tal-file path. With this information we look at the .tal file we call from more-tal, called more-wrapper:</p>
     157    <pre>
     158&lt;body
     159  xmlns:tal="http://common-lisp.net/project/bese/tal/core"
     160  xmlns:ucw="http://common-lisp.net/project/ucw/core"
     161  tal:in-package=":ucw-intro"&gt;
     162  &lt;tal:tal tal:content="$contents" tal:escape-html="nil"&gt;here goes more-tal&lt;/tal:tal&gt;
     163  &lt;tal:lisp&gt;
     164    (setf (da-var $little-class) "this is the new and quite boring contents of little class")
     165  &lt;/tal:lisp&gt;
     166  &lt;p tal:content="(da-var $little-class)"&gt;contents of little-class&lt;/p&gt;
     167&lt;/body&gt;
     168    </pre>
     169    <p>Should be pretty clear. For some more clarity, you could also have specified the file to include with:</p>
     170    <pre>
     171tal:name-expression="more${(print (string-downcase '-wrapper.tal))}"
     172    </pre>
     173    <p>Now granted, this looks rather useless and hackerish, but the point is to show how you can use arbitrary expressions enclosed in ${} to get to your filename.</p>
     174    <p>But when would you want to use name-expression? Well, imagine you want to reference a tal file based on the a component you have in a certain slot of the component you are rendering. Then you could write:</p>
     175    <p>&lt;tal:include tal:name-expression="details/${ (class-name (class-of (datum $component))) }"
     176                param:datum="(datum $component)"/&gt;</p>
     177    <p>This will include a different file in the details directory, depending on the class of the datum slot, and pass the datum object itself to the included file. (example and explanation from Marco Baringer)</p>
     178    <p>Note that the code inside ${} will only return the name of a class. tal:name-expression automagically appends .tal to the end if it's not already present, as does tal:name.</p>
     179    <h5>Ucw-specific tal</h5>
     180    <p>Ucw also has a couple of custom defined tal attributes and tags. They are:</p>
     181    <ul>
     182      <li>ucw:select - tag</li>
     183      <li>ucw:option - tag</li>
     184      <li>ucw:action - attribute</li>
     185      <li>ucw:accessor - attribute</li>
     186      <li>ucw:render-component - tag</li>
     187    </ul>
     188    <p>Which simply map to their yaclml equivalent, except for render-component which doesn't have one. Surprisingly enough it allows you to render a component from within tal. Typical well-formed tal strings using ucw would and actually do look like the tags below because they're straight from tal files found in the source code:</p>
     189    <pre>
     190&lt;a href="" ucw:action="(respond $component $value)" tal:content="$text"&gt;text&lt;/a&gt;
     191&lt;input type="file" ucw:accessor="(file-upload-example.file $component)"/&gt;
     192&lt;ucw:render-component ucw:component="$selected-component"/&gt;
     193    </pre>
     194    <p>Well, it should all be self-explanatory. Only render-component is slightly out of context, but even my obsessive over-explaining-gene doesn't feel the need to explain it.</p>
     195    <h5>Rendering tal files from within render methods</h5>
     196    <p>Sometimes you want to render tal files from within render methods. You can do this by using the render-template method, which is also used under the cover for children of template-component. A render-template method expects a request-context class, the location of a tal file and a tal environment. A basic one looks like this:</p>
     197    <pre>
     198(render-template ucw:*context* "tal-file.tal" nil)
     199    </pre>
     200    <p>In this example the method grabs the standard ucw context, but what is a context? From the source code:</p>
     201    <p>A request-context object contains all the information associated with one particular request/response loop. The request context is usually accessed via the special variable *context* and contains the currently relevant application, session, session-frame, request and response object.</p>
     202    <p>So you should almost always use ucw:*context*, unless you let the code do things advanced enough you don't need to read this tutorial to explain this particular aspect.</p>
     203    <p>Furthermore our example above specifies a tal file and a request context of nil. So if you want to render that particular tal file, all variables you want the file to look up in the request context will equate to nil.</p>
     204    <p>For explanations sake, we change the  tal-component component so it doesn't inherit from template-component anymore, eg change:</p>
     205    <pre>
     206(defcomponent tal-component (template-component)
     207  ...
     208    </pre>
     209    <p>to:</p>
     210    <pre>
     211(defcomponent  tal-component ()
     212  ...
     213    </pre>
     214    <p>Then we define a render method on the component:</p>
     215    <pre>
     216(defmethod render ((component tal-component))
     217        (render-template ucw:*context* "intro.tal" nil))
     218    </pre>
     219    <p>Now this one will actually report an error. Since our tal environment is nil, intro.tal tries to get to the slot component of an inexistent class. Let's add a class to our environment:</p>
     220    <pre>
     221(defmethod render ((component tal-component))
     222  (render-template ucw:*context* "intro.tal"  `(((component . ,component)))))
     223    </pre>
     224    <p>Since a tal-environment consists of lists of alists, components and hash tables intro.tal now finds our component by referencing the specified alist in the tal-environment. The $contents variable in the tal file however equates to nil, because the component itself isn't listed as an object the tal-environment references to look up values. To add both the component itself and use it as a variable we might as well use the function make-standard-environment which is meant for this purpose:</p>
     225    <pre>
     226(defmethod render ((component tal-component))
     227  (render-template ucw:*context* "intro.tal" (make-standard-environment `((component . ,component)) component)))
     228    </pre>
     229    <p>And now tal-component renders like before.</p>
     230
     231}}}
     232
     233[wiki:IntroNestedComponents Nested Components (:|,) containers and tabbed panes <- back] | [wiki:UcwIntro toc] | [wiki:IntroFormHandling forward -> Advanced form handling]