TypoScript Syntax and In-depth Study 1.3

来源:百度文库 编辑:神马文学网 时间:2024/07/03 09:13:38
1.3. Sorting out details
More about syntax, semantics and TypoScript compared to XML and XSLT
Ifyou think you perfectly understand TypoScript now (you mightalready...) then don‘t bother with this section. I even risk confusingyou again. But anyways, here it is - more theoretical information onTypoScript including references to the relationship between XML andXSLT:
XML and TypoScript - all about syntax:
A chunk of"TypoScript code" is like an XML document - it only containsinformation in a structured way, nothing else.  But in order to storeinformation in TypoScript or XML you need to follow the syntax - rulesabout how the information values can be  inserted in the structure.Like the grammar for a human language defines in which order words canbe combined.
For XML such rules include that "all tags must beended, eg. ... or
", correct nesting,using lowercase for element and attribute names etc. If you followthese rules an XML document is called "well formed". For TypoScriptsimilar rules exist like "The = operator assigns the rest of the textstring as the value to the preceeding object path" or "A line startingwith # or / is a comment and therefore ignored".
XSLT and "TypoScript Templates" - all about semantics (meaning, function):
This is syntactically valid XML:
qwerty
And this is syntactically valid TypoScript:
asdf = qwerty
And this is syntactically valid English:
footballs sing red
Butnone of these examples make sense without some reference which defineshow elements, values and words can be combined in order to form meaning- they need a context. This is called semantics. For human languages wehave it internally because we know footballs can‘t sing and you can‘t"sing red" - we know it‘s nonsense while the sentence is correctlyformed. For an XML document you have it by the DTD or schema whichdefines if the element "" exists on that level in thedocument (and if not, then it‘s nonsense) and for TypoScript you haveit by the reference document for the context where the TypoScriptsyntax is used to define an information hierarchy - for instance the"TSref" for TypoScript Templates or the "TSconfig" document for "PageTSconfig" or "User TSconfig".
So an XML document makes sense onlyif you know the relationship of the information stored inside of thedocument and that is required if you want an XSLT stylesheet totransform one XML document to another document. In fact an XSLTstylesheet is like babelfish for XML - it translate one "language" ofXML into another "language" of XML.
Similarly TypoScript is usedas the syntax to build "TypoScript Templates" (containing semantics -meaning); the information only makes sense if it follows the rulesdefined in the "TSref" document.
BTW, the comparison of"TypoScript Templates" and "XSLT" is intensional since both can bedescribed as declarational programming languages  - programming byconfiguring values which instructs a real procedural program  (eg. theTypoScript Frontend Engine which is written in PHP) how to output data.More is written on this issue on typo3.org.
For more onsyntax and semantics, you can read this link that I found on the net.
Where is TypoScript used?
Thisquestion cannot be answered completely since this document onlydescribes the syntax of TypoScript and not any of the contexts whereTypoScript syntax is applied for configuration; theoretically anyonecould use the TypoScript parser class in TYPO3 to generateconfiguration for their own local extensions using their own local"semantics" (seeanother chapter in this document).
But at least we can mention the three main applications of the TypoScript syntax as used in TYPO3s core parts:
Page TSconfig - customization of branches of the Page tree.
User TSconfig - customization of users and their groups.
TypoScript Templates - definition and customization of each website found in the page tree.
Page TSconfig
Eachpage record in TYPO3 has a field where you can enter "TSconfig". Themain idea with Page TSconfig is that you can configure individualbehavior for separate parts of the page tree. This is possible becausethe TypoScript code entered in the TSconfig fields is accumulated forall pages in the root line of the current position in the page treestarting from the root and going outwards. Thus TypoScript settings inTSconfig fields of outer pages can override those settings of pagescloser to the root.
For instance you may have two separatewebsites  located in separate branches of the page tree. The onewebsite might support content from only the "normal" column while theother website supports it for both the "normal" and "border" column.Since the Page module by default shows all four possible columns youmay want to instruct the page module to show only the normal column andnormal + border column respectively. But this will only be possible ifyou can somehow tell the system that from this page and outwards, useonly "normal" column and from that page and outwards use only "normal"+ "border" column. So in the root page of the two-column website youenter this line in the TSconfig field:

And likewise for the one-column website you enter this value in the TSconfig field of the root page:

Now the "Page" module will receive the value of theproperty "colPos_list"when showing the page content available for any subpage of the rootpage where the configuration was entered. Accordingly only theconfigured columns will be shown.
The objects and properties you can use here is generally defined in thedocument "TSConfig" in addition to local extension documents.
User TSconfig
Eachfrontend and backend user and group has a field for input of TSconfig.The main idea with User TSconfig is that you can configure individualbehavior for groups and even users themselves. The possibilities arenormally settings which are on a more detailed level than what you canalready set as permission settings in the main forms for users/groups.For instance you could configure how many clipboard pads a user shouldsee or whether a "Save document and add new" button should appear forall forms for this user - stuff which is clearly too detailed for aspot in the main form for permissions and settings.
Like withPage TSconfig the content of the TSconfig fields are accumulated in acertain order; the order of member groups and finally the users ownfields settings. Thus a setting for a user will override the settingfor one of his member groups.
To mention an example of what youcan do with User TSconfig for a backend user, then this line willenable the "Save document and create new" button in editing forms:

The objects and properties you can use here is generally defined in thedocument "TSConfig" in addition to local extension documents.
TypoScript Templates
Themost (in)famous and extensive use of TypoScript is in the frontendengine where TypoScript is used to configure how the frontend enginewill put together the website output. This is probably also whereTypoScript clashes most with traditional ideas of template building inweb design and confuses people to think of TypoScript as a programminglanguage - with the result that they find it even more confusing. (IfTYPO3 has a scripting language it is not TypoScript  but PHP!)
Thisintroduction to TypoScript tries to eliminate this confusion andtherefore let us make two statements about how TYPO3 handles templates:
No fixed template method: TYPO3 does not offer one fixed way to dealing with templates for websites; rather you are set free to choose the way you find most appealing. You can:
HTML templates; configure TYPO3 to facilitate external HTML-templates with markers and subparts. Popular and familiar for most people. Please see the tutorial"Modern Template Building, Part 1".
Ext. Templating Engines: configure TYPO3 to use XSLT stylesheets with an XSLT processor. This is done either by an extension providing this functionality or by writing your own extension for it.
Custom PHP: configure TYPO3 to call your own PHP-code which generates content in any way you may prefer. This might include using third party templating engines!
TS content objects: or build the page by the Frontend Engines "content objects" which are accessible/programmable through the TypoScript syntax.
TypoScript Templates determines the method: No matter which template method (see list above) you would like to use TYPO3 needs to be told which one! And this is what the TypoScript Template does first and foremost; it is used to configure basic and advanced behaviors of the frontend engine so that the site rendering gets done.
ATypoScript Template works a little like the Page TSconfig; it is adatabase record attaching its TypoScript content to a certain page andfrom that page and outwards the configuration contained in theTypoScript will affect the pages until a new template record is foundwhich overrides content from earlier in the tree. Thus TypoScriptTemplate records are effectively defining which page is the root pageof a website:

TypoScriptTemplates contain a field for the TypoScript configuration code("Setup" field) but a template record like the one on the picture above("NEW typo3.org") can also contain references to other template recordsand files which contain predefined generally useful TypoScript codewhich is included and thus reusable/sharable across templates. Theorder of included TypoScript template records / files can be visuallyseen with the Template Analyzer extension (tstemplate_analyzer):

To get more background knowledge abouthow TypoScript templates work please read the document TypoScript Templates. To read about all standard objects and properties you can use in building TypoScript templates you should refer toTypoScript reference - TSref. For practical examples when you want tolearn by doing, look at TypoScript by Example.
Entering TypoScript
SinceTypoScript has a line-based syntax which most of all resembles what isfound in simple text based configuration files it is also authored inordinary textarea input fields inside of TYPO3. An example is the"TSconfig" box of a regular page header:

Thisis typically how TypoScript is entered - directly in form fields. Nosyntax highlighting, no way of using TAB stops, no linenumber countingetc. Quite boring and rudimentary. Of course the lack of such featuresis not a political manifest but rather the lack of the ability tocreate such features with a simple textarea. Could anyone provide anice Java-editor instead we would be happy. (In the meantime you canfind TypoScript syntax highlighting for certain text editors. Ask onthe mailing lists or search typo3.org).
However there are some helpful features:
a) There is the "TS wizard" icon which is often found to the right of the textarea - this can help you finding properties for the current TypoScript context
b) there also is the ability to insert an include-tag in any TypoScript field (see later in this document) which refers to an external file which can contain TypoScript - and that file can be edited with an external editor with whatever benefits that has.
Parsing, Storing and Executing TypoScript
Parsing TypoScript
Thismeans that the TypoScript text content is transformed into a PHP arraystructure by following the rules of the TypoScript syntax. But stillthe meaning of the parsed content is not evaluated.
Duringparsing, syntax errors may occur when the input TypoScript text contentdoes not follow the rules of the TypoScript syntax. The parser ishowever very forgiving in that case and it only registers an errorinternally while it will continue to parse the TypoScript code. Syntaxerrors can therefore  be seen only with a tool that analyzes the syntax- like the syntax highlighter does.
The class "t3lib_tsparser" is used to parse TypoScript content. Please see another chapter in this document for details.
Storing parsed TypoScript
WhenTypoScript has been parsed it is stored in a PHP array (which is oftenserialized and cached in the database afterward). If you take theTypoScript from the introduction examples and parses it you will get aresult like below:
First, the TypoScript:
asdf = qwertyasdf {  zxcvbnm = uiop  backgroundColor = blue  backgroundColor.transparency = 95%
}
Thenafter parsing it with the function "parse()" in the t3lib_tsparserclass the internal variable $this->setup in that class will containa PHP array which looks like this (with the print_r() PHP function):
Array(    [asdf] => qwerty    [asdf.] => Array        (            [zxcvbnm] => uiop            [backgroundColor] => blue            [backgroundColor.] => Array                (                    [transparency] => 95%                )        ))
Youcan also print the array by an API function in TYPO3, namelyt3lib_div::view_array() or just debug(). Then it looks like this:

As you see the value ("blue") of the property "backgroundColor" can be fetched by this PHP code:
$this->setup[‘asdf.‘][‘backgroundColor‘]
Soyou can say that TypoScript offers a textbased interface for gettingvalues into a multidimensional PHP array from a simple text field orfile. This can be very useful if you need to take that kind of inputfrom users without giving them direct access to PHP code - hence thereason why TypoScript came into existence.
"Executing" TypoScript
SinceTypoScript itself contains only information (!) you cannot "execute"it. The closest you come to "executing" TypoScript is when you take thePHP array with the parsed TypoScript structure and passes it to a PHPfunction which then  performs whatever actions according to the valuesfound in the array. This is the syntax/semantics debate again.
Syntax highlighting and debugging
Syntaxhighlighting of TypoScript code is done by various analysisapplications in TYPO3 like the Template Analyzer for TypoScriptTemplates or the User Admin module or Page TSconfig function in theInfo module. These typically allows you to view the TypoScript in eachcontext highlighted with syntax.
Here is an example from Page TSconfig:

In the extension "extdeveval" you will also find a tool, "Code highlighting", which can analyse TypoScript code adhoc:

There are various modes of display:

The analytic mode (displayed above) colors all parts of the syntax:
Object and property names gets light blue background (#1)
Values get a yellow background (#2)
Whitespace becomes olive green in the background (#3)
Operators are colored with a brown background
Another mode is the "Block mode", which simply indents the TypoScript code:

Finally you will be warned if syntax errors are found and ignored data will also be highlighted in green:

Debugging
DebuggingTypoScript for syntax errors can be done with this tool and any otherplace where the syntax highlighter is used. But this will only tell youif something is syntactically wrong with the code - whether you combineobjects and properties semantically correctly depends on the contextand cannot be told by the TypoScript parser itself.
Currentlyno tools exist to do semantically checking for either TypoScriptTemplates, Page TSconfig or User TSconfig (writing summer 2003)
(This tool for syntax highlighting is available from TYPO3 version 3.6.0)
Myths, FAQ and Acknowledgements
Thispage is the final word in this introduction chapter to the TypoScriptsyntax. It contains a few remarks and answers to questions you maystill have. So here it goes:
Myth: "TypoScript is a scripting language"
Thisis misleading to say since you will think that TypoScript is like PHPor JavaScript while it is not. From the previous pages you have learnedthat TypoScript strictly speaking is just a syntax. However when theTypoScript syntax is applied to create TypoScript Templates then itbegins to look like programming and the parallel to XSLT might alsohint at that.
In any case TypoScript is NOT a comparable to ascripting language like PHP or JavaScript. In fact, if TYPO3 offers anyscripting language it is PHP itself! TypoScript is only an API which isoften used to configure underlying PHP code.
Finally; The name "TypoScript" is misleading as well. We are sorry about that, too late to change now.
Myth: "TypoScript has the same syntax as JavaScript"
TypoScriptwas designed to be simple to use and understand. Therefore the syntaxlooks like JavaScript objects to some degree. But again; it‘s verydangerous to say this since it all stops with the syntax - TypoScriptis still not a procedural programming language!
Myth: "TypoScript is a proprietary standard"
SinceTypoScript is not a scripting language it does not make sense to claimthis in comparison to PHP, JavaScript, Java or whatever scriptinglanguage.
However compared to XML or PHP arrays (which alsocontain information) you can say that TypoScript is a proprietarysyntax since a PHP array or XML file could be used to contain the sameinformation as TypoScript does. But this is not a drawback: For storageand exchange of content TYPO3 uses SQL (or XML if you need to), forstorage of configuration values XML is not suitable anyways -TypoScript is much better at that job (see below).
To claim thatTypoScript is a proprietary standard as an argument against TYPO3 isreally unfair since the claim makes it sound like TypoScript is a wholenew programming language or likewise. Yes, the TypoScript syntax isproprietary but extremely useful and when you get the hang of it it isvery easy to use. In all other cases TYPO3 uses official standards likePHP, SQL, XML, XHTML etc. for all external data storage andmanipulation.
The most complex use of TypoScript is probably withthe TypoScript Template Records. It is understandable that TypoScripthas earned a reputation of being complex when you consider how much ofthe Frontend Engine you can configure through TypoScript Templaterecords. But basically TypoScript is just an API to the PHP functionsunderneath. And if you think there are a lot of options there it wouldbe no better if you were to use the PHP functions directly! Then therewould be maybe even more API documentation to explain the API and youwouldn‘t have the streamlined abstraction provided by TypoScriptTemplates. This just served to say: The amount of features and the timeit would take to learn about them would not be eliminated if TypoScriptwere not made!
Myth: "TypoScript is very complex"
TypoScriptis simple in nature. But certainly it can quickly become complex andget "out of hand" when the amount of code lines grows! This can partlybe solved by:
Disciplined coding: Organize your TypoScript in a way that you can visually comprehend.
Use the Syntax Highlighter to analyze and clean up your code - this gives you overview as well.
Why not XML instead?
Afew times TypoScript has been compared with XML since both "languages"are frameworks for storing information. Apart from XML being a W3Cstandard (and TypoScript still not... :-) the main difference is thatXML is great for large amounts of information with a high degree of"precision" while TypoScript is great for small amounts of "adhoc"information - like configuration values normally are.
Actuallya data structure defined in TypoScript could also have been modeled inXML. Currently you cannot use XML as an alternative to TypoScript(writing of June 2003) but this may happen at some point. Lets presentthis fictitious example of how a TypoScript structure could also havebeen implemented in "TSML" (our fictitious name for the non-existingTypoScript-Mark Up Language):
styles.content.bulletlist = TEXTstyles.content.bulletlist {  current = 1  trim = 1  if.isTrue.current = 1        # Copying the object "styles.content.parseFunc" to this position  parseFunc < styles.content.parseFunc  split {    token.char = 10    cObjNum = 1    1.current < .cObjNum    1.wrap =
  •   }    # Setting wrapping value:  fontTag =
      |
      textStyle.altWrap = {$styles.content.bulletlist.altWrap}
    }
    That was 17 lines of TypoScript code and converting this information into an XML structure could look like this:
                                            TEXT                1                1                                                            1                                                                                                                                  10                                        1                                            1                        <li>                                                                      <ol type="1"> | </ol>                                    {$styles.content.bulletlist.altWrap}                                       

    Thatwas 33 lines of XML - the double amount of lines! And in bytes probablyalso much bigger. This example clearly demonstrates why not XML! XMLwill just get in the way, it is not handy for what TypoScript normallydoes. But hopefully you can at least use this example in yourunderstand of what TypoScript is compared to XML.
    The reasonableapplication for using XML as an alternative to TypoScript is if an XMLeditor existed which in some way makes the entering of XML data into astructure like this possible and easy.