You are on page 1of 7

11/8/2014

QWeb

Navigation
Navigation
QWeb

Table Of Contents (../)


QWeb
API
Directives
DefiningTemplates
Output
FlowControl
TemplateInheritanceand
Extension
EscapeHatches/debugging

Versions
trunk
server(/trunk/server/)
website_payment
(/trunk/website_payment/)
website_event
(/trunk/website_event/)
website_blog
(/trunk/website_blog/)
crm(/trunk/crm/)
hr_recruitment
(/trunk/hr_recruitment/)
web_kanban_gauge
(/trunk/web_kanban_gauge/)
project_issue
(/trunk/project_issue/)
mail(/trunk/mail/)
mass_mailing
(/trunk/mass_mailing/)
web_kanban_sparkline
(/trunk/web_kanban_sparkline/)
web_graph(/trunk/web_graph/)
web(/trunk/web/)
email_template
(/trunk/email_template/)
hw_proxy(/trunk/hw_proxy/)
project(/trunk/project/)
hr_holidays
(/trunk/hr_holidays/)

QWeb
QWebisthetemplateengineusedbytheOpenERPWebClient.ItisanXMLbasedtemplatinglanguage,
similartoGenshi(http://en.wikipedia.org/wiki/Genshi_(templating_language)),Thymeleaf
(http://en.wikipedia.org/wiki/Thymeleaf)orFacelets(http://en.wikipedia.org/wiki/Facelets)withafew
peculiarities:
It'simplementedfullyinjavascriptandrenderedinthebrowser.
Eachtemplatefile(XMLfiles)containsmultipletemplates,wheretemplateengineusuallyhavea1:1
mappingbetweentemplatefilesandtemplates.
IthasspecialsupportinOpenERPWeb's Widget,thoughitcanbeusedoutsideofOpenERPWeb
(andit'spossibletouse WidgetwithoutrelyingontheQWebintegration).
TherationalebehindusingQWebinsteadofamorepopulartemplatesyntaxisthatitsextension
mechanismisverysimilartotheopenerpviewinheritancemechanism.LikeopenerpviewsaQWeb
templateisanxmltreeandthereforexpathordommanipulationsareeasytoperformsonit.
Here'sanexampledemonstratingmostofthebasicQWebfeatures:
<templates>
<divtname="example_template"tattfclass="base#{cls}">
<h4tif="title"><ttesc="title"/></h4>
<ul>
<litforeach="items"tas="item"tattclass="item_parity">
<ttcall="example_template.sub">
<ttset="arg"tvalue="item_value"/>
</t>
</li>
</ul>
</div>
<ttname="example_template.sub">
<ttesc="arg.name"/>
<dl>
<ttforeach="arg.tags"tas="tag"tif="tag_indexlt5">
<dt><ttesc="tag"/></dt>
<dd><ttesc="tag_value"/></dd>
</t>
</dl>
</t>
</templates>

renderedwiththefollowingcontext:
{
"class1":"foo",
"title":"RandomTitle",
"items":[
{"name":"foo","tags":{"bar":"baz","qux":"quux"}},
{"name":"Lorem","tags":{
"ipsum":"dolor",
"sit":"amet",
"consectetur":"adipiscing",
"elit":"Sed",
"hendrerit":"ullamcorper",
"ante":"id",
"vestibulum":"Lorem",
"ipsum":"dolor",
"sit":"amet"
}
}
]
}

willyieldthissectionofHTMLdocument(reformatedforreadability):

training(/trunk/training/)
7.0(/7.0/)
https://doc.odoo.com/trunk/web/qweb/

1/7

11/8/2014

ar(/7.0/ar/) de(/7.0/de/)
el(/7.0/el/) es(/7.0/es/)
fr(/7.0/fr/) hr(/7.0/hr/)
id(/7.0/id/) it(/7.0/it/)
ja(/7.0/ja/) lt(/7.0/lt/)
pl(/7.0/pl/)
pt_BR(/7.0/pt_BR/)
ro(/7.0/ro/) ru(/7.0/ru/)
th(/7.0/th/) tr(/7.0/tr/)
vi(/7.0/vi/)
zh_CN(/7.0/zh_CN/)
6.1(/6.1/)
ar(/6.1/ar/) de(/6.1/de/)
el(/6.1/el/) es(/6.1/es/)
fr(/6.1/fr/) hr(/6.1/hr/)
id(/6.1/id/) it(/6.1/it/)

QWeb
<divclass="basefoo">
<h4>RandomTitle</h4>
<ul>
<liclass="even">
foo
<dl>
<dt>bar</dt>
<dd>baz</dd>
<dt>qux</dt>
<dd>quux</dd>
</dl>
</li>
<liclass="odd">
Lorem
<dl>
<dt>ipsum</dt>
<dd>dolor</dd>
<dt>sit</dt>
<dd>amet</dd>
<dt>consectetur</dt>
<dd>adipiscing</dd>
<dt>elit</dt>
<dd>Sed</dd>
<dt>hendrerit</dt>
<dd>ullamcorper</dd>
</dl>
</li>
</ul>
</div>

ja(/6.1/ja/) lt(/6.1/lt/)
pl(/6.1/pl/)

API

pt_BR(/6.1/pt_BR/)

WhileQWebimplementsanumberofattributesandmethodsforcustomizationandconfiguration,onlytwo
thingsarereallyimportanttotheuser:

ro(/6.1/ro/) ru(/6.1/ru/)
tr(/6.1/tr/) vi(/6.1/vi/)
zh_CN(/6.1/zh_CN/)
6.0(/6.0/)
ar(/6.0/ar/) de(/6.0/de/)
el(/6.0/el/) es(/6.0/es/)
fr(/6.0/fr/) hr(/6.0/hr/)

classQWeb2.Engine()

TheQWeb"renderer",handlesmostofQWeb'slogic(loading,parsing,compilingandrendering
templates).
OpenERPWebinstantiatesonefortheuser,andsetsitto instance.web.qweb.Italsoloadsallthe
templatefilesofthevariousmodulesintothatQWebinstance.
A QWeb2.Engine()alsoservesasa"templatenamespace".
QWeb2.Engine.render(template[,context])

RendersapreviouslyloadedtemplatetoaString,using context(ifprovided)tofindthevariables
accessedduringtemplaterendering(e.g.stringstodisplay).
Arguments:

template(String)thenameofthetemplatetorender

id(/6.0/id/) it(/6.0/it/)
ja(/6.0/ja/) lt(/6.0/lt/)

context(Object)thebasicnamespacetousefortemplaterendering
Returns:

String

pl(/6.0/pl/)

ro(/6.0/ro/) ru(/6.0/ru/)

Theengineexposesanothermethodwhichmaybeusefulinsomecases(e.g.ifyouneedaseparate
templatenamespacewith,inOpenERPWeb,Kanbanviewsgettheirown QWeb2.Engine()instanceso
theirtemplatesdon'tcollidewithmoregeneral"module"templates):

tr(/6.0/tr/) vi(/6.0/vi/)

QWeb2.Engine.add_template(templates)

pt_BR(/6.0/pt_BR/)

zh_CN(/6.0/zh_CN/)
5.0(/5.0/)
ar(/5.0/ar/) de(/5.0/de/)
el(/5.0/el/) es(/5.0/es/)
fr(/5.0/fr/) hr(/5.0/hr/)
id(/5.0/id/) it(/5.0/it/)
ja(/5.0/ja/) lt(/5.0/lt/)
pl(/5.0/pl/)

Loadsatemplatefile(acollectionoftemplates)intheQWebinstance.Thetemplatescanbespecifiedas:
AnXMLstring
QWebwillattempttoparseittoanXMLdocumentthenloadit.
AURL
QWebwillattempttodownloadtheURLcontent,thenloadtheresultingXMLstring.
A Documentor Node
QWebwilltraversethefirstlevelofthedocument(thechildnodesoftheprovidedroot)andloadany
namedtemplateortemplateoverride.

A QWeb2.Engine()alsoexposesvariousattributesforbehaviorcustomization:
QWeb2.Engine.prefix

https://doc.odoo.com/trunk/web/qweb/

2/7

11/8/2014

QWeb

pt_BR(/5.0/pt_BR/)

Prefixusedtorecognizedirectivesduringparsing.Astring.Bydefault, t.

ro(/5.0/ro/) ru(/5.0/ru/)

QWeb2.Engine.debug

tr(/5.0/tr/) vi(/5.0/vi/)

Booleanflagputtingtheenginein"debugmode".Normally,QWebinterceptsanyerrorraisedduring
templateexecution.Indebugmode,itleavesallexceptionsgothroughwithoutinterceptingthem.

zh_CN(/5.0/zh_CN/)

QWeb2.Engine.jQuery

ThejQueryinstanceusedduringtemplateinheritanceprocessing.Defaultsto window.jQuery.

DownloadfreeEbooks
(https://www.odoo.com/ebooks)
Startyourfreetrial
(https://www.odoo.com/start)

QWeb2.Engine.preprocess_node
A Function.Ifpresent,calledbeforecompilingeachDOMnodetotemplatecode.InOpenERPWeb,this
isusedtoautomaticallytranslatetextcontentandsomeattributesintemplates.Defaultsto null.

Directives
AbasicQWebtemplateisnothingmorethananXHTMLdocument(asitmustbevalidXML),whichwillbe
outputasis.Buttherenderingcanbecustomizedwithbitsoflogiccalled"directives".Directivesare
attributeselementsprefixedby prefix(thisdocumentwillusethedefaultprefix t,asdoesOpenERP
Web).
Adirectivewillusuallycontroloraltertheoutputoftheelementitisseton.Ifnosuitableelementis
available,theprefixitselfcanbeusedasa"nooperation"elementsolelyforsupportingdirectives(or
internalcontent,whichwillberendered).Thismeans:
<t>Somethingsomething</t>

willsimplyoutputthestring"Somethingsomething"(theelementitselfwillbeskippedand"unwrapped"):
vare=newQWeb2.Engine()
e.add_template('<templates>\
<ttname="test1"><t>Test1</t></t>\
<ttname="test2"><span>Test2</span></t>\
</templates>')
e.render('test1')//Test1
e.render('test2')//<span>Test2</span>

Note
Theconventionsusedindirectivedescriptionsarethefollowing:
directivesaredescribedascompoundfunctions,potentiallywithoptionalsections.Eachsectionof
thefunctionnameisanattributeoftheelementbearingthedirective.
aspecialparameteris BODY,whichdoesnothaveanameanddesignatesthecontentofthe
element.
specialparametertypes(asidefrom BODYwhichremainsuntyped)are Name,whichdesignatesa
validjavascriptvariablename, Expressionwhichdesignatesavalidjavascriptexpression,and
FormatwhichdesignatesaRubystyleformatstring(aliteralstringwith #{Expression}
inclusionsexecutedandreplacedbytheirresult)
Note
Expressionactuallysupportsafewextensionsonthejavascriptsyntax:becausesomesyntactic
elementsofjavascriptarenotcompatiblewithXMLandmustbeescaped,textsubstitutionsareperformed
fromformswhichdon'tneedtobeescaped.Thusthefollowing"keywordoperators"areavailableinan
Expression: and(mapsto &&), or(mapsto ||), gt(mapsto >), gte(mapsto >=), lt(mapsto
<)and lte(mapsto <=).

Defining Templates
t-name=name

Parameters: name(String)
anarbitraryjavascriptstring.Eachtemplatenameisuniqueinagiven QWeb2.Engine()
instance,defininganewtemplatewithanexistingnamewilloverwritethepreviousone
withoutwarning.
Whenmultipletemplatesarerelated,itiscustomarytousedottednamesasakindof
"namespace"e.g. fooand foo.barwhichwillbeusedeitherby fooorbyasub
widgetofthewidgetusedby foo.

https://doc.odoo.com/trunk/web/qweb/

3/7

11/8/2014

QWeb

Templatescanonlybedefinedasthechildrenofthedocumentroot.Thedocumentroot'snameis
irrelevant(it'snotchecked)butisusually <templates>forsimplicity.
<templates>
<ttname="template1">
<!templatecode>
</t>
</templates>
tnamecanbeusedonanelementwithanoutputaswell:
<templates>
<divtname="template2">
<!templatecode>
</div>
</templates>

whichensuresthetemplatehasasingleroot(ifatemplatehasmultiplerootsandisthenpasseddirectlyto
jQuery,oddthingsoccur).

Output
t-esc=content

Parameters: content(Expression)
Evaluates,htmlescapesandoutputs content.
t-raw=content

Parameters: content(Expression)
Similartotescbutdoesnothtmlescapetheresultofevaluating content.Shouldonlyeverbeusedfor
knownsecurecontent,orwillbeanXSSattackvector.
t-att=map

Parameters: map(Expression)
Evaluates mapexpectingan Objectresult,setseachkey:valuepairasanattribute(anditsvalue)onthe
holderelement:
<spantatt="{foo:3,bar:42}"/>

willyield
<spanfoo="3"bar="42"/>

t-att-ATTNAME=value

Parameters:

ATTNAME(Name)
value(Expression)

Evaluates valueandsetsitontheattribute ATTNAMEontheholderelement.


If value'sresultis undefined,suppressesthecreationoftheattribute.
t-attf-ATTNAME=value

Parameters:

ATTNAME(Name)
value(Format)

Similartotatt*butthevalueoftheattributeisspecifiedviaa Formatinsteadofanexpression.Usefulfor
specifyinge.g.classesmixingliteralclassesandcomputedones.

Flow Control
t-set=name (t-value=value | BODY)

Parameters:

name(Name)
value(Expression)
BODY

Createsanewbindinginthetemplatecontext.If valueisspecified,evaluatesitandsetsittothe
specified name.Otherwise,processes BODYandusesthatinstead.
t-if=condition

https://doc.odoo.com/trunk/web/qweb/

4/7

11/8/2014

QWeb

Parameters: condition(Expression)
Evaluates condition,suppressestheoutputoftheholderelementanditscontentoftheresultisfalsy.
t-foreach=iterable [t-as=name]

Parameters:

iterable(Expression)
name(Name)

Evaluates iterable,iteratesonitandevaluatestheholderelementanditsbodyonceperiterationround.
If nameisnotspecified,computesa namebasedon iterable(byreplacingnon Namecharactersby
_).
If iterableyieldsa Number,treatsitasarangefrom0tothatnumber(excluded).
Whileiterating,tforeachaddsanumberofvariablesinthecontext:
#{name}

Ifiteratingonanarray(orarange),thecurrentvalueintheiteration.Ifiteratingonanobject,thecurrent
key.
#{name}_all

Thecollectionbeingiterated(thearraygeneratedfora Number)
#{name}_value

Thecurrentiterationvalue(currentitemforanarray,valueforthecurrentitemforanobject)
#{name}_index

The0basedindexofthecurrentiterationround.
#{name}_first

Whetherthecurrentiterationroundisthefirstone.
#{name}_parity
"odd"ifthecurrentiterationroundisodd, "even"otherwise. 0isconsideredeven.
t-call=template [BODY]

Parameters:

template(String)
BODY

Callsthespecified templateandreturnsitsresult.If BODYisspecified,itisevaluatedbeforecalling


templateandcanbeusedtospecifye.g.parameters.Thisusageissimilartocalltemplatewithwith
paraminXSLT(http://zvon.org/xxl/XSLTreference/OutputOverview/xslt_withparam_frame.html).

Template Inheritance and Extension


t-extend=template BODY

Parameters: template(String)nameofthetemplatetoextend
WorkssimilarlytoOpenERPmodels:ifusedonitsown,willalterthespecifiedtemplateinplaceifusedin
conjunctionwithtnamewillcreateanewtemplateusingtheoldoneasabase.
BODYshouldbeasequenceoftjqueryalterationdirectives.

Note
Theinheritanceinthesecondformisstatic:theparenttemplateiscopiedandtransformedwhentextendis
called.Ifitisalteredlater(byatextendwithoutatname),thesechangeswillnotappearinthe"child"
templates.
t-jquery=selector [t-operation=operation] BODY

Parameters:

selector(String)aCSSselectorintotheparenttemplate
operationoneof append, prepend, before, after, inneror replace.
BODY operationargument,oralterationstoperform

If operationisspecified,appliestheselectortotheparenttemplatetofindacontextnode,then
applies operation(asajQueryoperation)tothecontextnode,passing BODYasparameter.
Note
replacemapstojQuery'sreplaceWith(newContent)(http://api.jquery.com/replaceWith/), inner
mapstohtml(htmlString)(http://api.jquery.com/html/).

If operationisnotprovided, BODYisevaluatedasjavascriptcode,withthecontextnodeas this.


Warning

https://doc.odoo.com/trunk/web/qweb/

5/7

11/8/2014

QWeb

Whilethissecondformismuchmorepowerfulthanthefirst,itisalsomuchhardertoreadand
maintainandshouldbeavoided.Itisusuallypossibletoeitheravoiditorreplaceitwithasequence
of t-jquery:t-operation:.

Escape Hatches / debugging


t-log=expression

Parameters: expression(Expression)
Evaluatestheprovidedexpression(inthecurrenttemplatecontext)andlogsitsresultvia console.log.
t-debug

Injectsadebuggerbreakpoint(viathe debugger;statement)inthecompiledtemplateoutput.
t-js=context BODY

Parameters:

context(Name)
BODYjavascriptcode

Injectstheprovided BODYjavascriptcodeintothecompiledtemplate,passingitthecurrenttemplate
contextusingthenamespecifiedby context.

Learn
Demo(//www.odoo.com/saas_master/demo)
Help(//www.odoo.com/forum/Help1)
Documentation(//www.odoo.com/page/documentation)
Presentations(http://www.slideshare.net/openobject)
Videos(https://www.youtube.com/user/OpenERPonline)
EducationProgram(//www.odoo.com/page/educationprogram)

Open Source
GitHub(https://github.com/odoo)
Download(//www.odoo.com/page/download)
MailingLists(//www.odoo.com/page/odoocommunity)
Community(//www.odoo.com/page/community)
ContinuousIntegration(http://runbot.openerp.com/)
ReportaBug(https://github.com/odoo/odoo/issues)
Translate

Services
Pricing(//www.odoo.com/page/pricing)
Trainings(//www.odoo.com/event)
PointofSalesMaterials(//www.odoo.com/shop/category/PointofSaleHardware3)
FindaPartner(//www.odoo.com/partners)
BecomeaPartner(//www.odoo.com/page/becomeapartner)
FindanExpert(//www.odoo.com/certifications)

About us
Contactus(//www.odoo.com/page/contactus)
Aboutus(//www.odoo.com/page/aboutus)
OurCustomers(//www.odoo.com/page/cases)
Events(//www.odoo.com/event)
Blogs(//www.odoo.com/blog/OpenERPBlogPost1)
https://doc.odoo.com/trunk/web/qweb/

6/7

11/8/2014

QWeb

Jobs(//www.odoo.com/jobs)
Twitter(https://twitter.com/Odooapps)
Facebook(https://www.facebook.com/odooapps)
LinkedIn(https://www.linkedin.com/company/odoo)
Google+(https://plus.google.com/u/0/100883176139028080672/posts)

Apps to Boost Sales


CRM(//www.odoo.com/page/crm)
PointofSales(//www.odoo.com/page/pointofsale)
QuoteBuilder(//www.odoo.com/page/quotebuilder)
MassMailing(//www.odoo.com/page/mailing)
Survey(//www.odoo.com/page/survey)
Events(//www.odoo.com/page/events)
CommunityBuilder(//www.odoo.com/page/website.communitybuilder)
LeadAutomation(//www.odoo.com/page/leadautomation)
LiveChat(//www.odoo.com/page/livechat)

Apps to Build Websites


CMS(//www.odoo.com/page/websitebuilder)
eCommerce(//www.odoo.com/page/ecommerce)
Blogs(//www.odoo.com/page/blogengine)
Forum(//www.odoo.com/page/website.communitybuilder)

Apps to Run Operations


ProjectManagement(//www.odoo.com/page/projectmanagement)
Billing(//www.odoo.com/page/billing)
Accounting(//www.odoo.com/page/accounting)
WarehouseManagement(//www.odoo.com/page/warehouse)
Manufacturing(//www.odoo.com/page/manufacturing)
Procurements(//www.odoo.com/page/purchase)

Apps to Delight Employees


EmployeesDirectory(//www.odoo.com/page/employees)
EnterpriseSocialNetwork(//www.odoo.com/page/enterprisesocialnetwork)
Recruitment(//www.odoo.com/page/recruitment)
Expenses(//www.odoo.com/page/expenses)
Appraisals(//www.odoo.com/page/appraisal)
Fleet(//www.odoo.com/page/fleet)
CopyrightOdoo.

https://doc.odoo.com/trunk/web/qweb/

7/7

You might also like