28 Feb 2010
Dojo AttributeMap
When using Dojo templating, most guides on the web suggest using ${variable} in your template, where variable is the name of one of your widget’s attributes. When writing my first custom widget, I couldn’t get this to work; no matter what I tried the templating engine would not replace ${} blocks.
Frantically searching for a solution, I found numerous references to using an “attribute map” instead of ${}, but the documentation was pretty poor.
Basically, you can add an attribute map by declaring an attribute in your widget called attributeMap. You then perform a mapping between attribute name in your widget and node in your template.
dojo.declare(
'customWidgets.MyWidget',
[dijit._Widget, dijit._Templated],
{
variable : 'myVar',
attributeMap : {
// key is attribute name, value is node identifier
variable : 'myNode',
},
templatePath :
new dojo.moduleUrl('customWidgets', 'MyWidget.html')
}
);
This seems pretty straightforward. Except… well:
- What is
myNode - What part of
myNodedoes it bind to?
In your template, you need to declare a dojoAttachPoint, which will become your node. This is pretty straightforward:
<div dojoAttachPoint="myNode"></div>
For point 2, what this will actually do, is create an HTML attribute called variable in your <div>, i.e.
<div variable="myVar"></div>
This may or may not be useful. You can invoke this behaviour more explicitly
attributeMap : {
variable : {
node : 'myNode',
type : 'attribute'
}
},
If you want the div‘s contents to take your value, you can set type to innerHTML. The bit of info that’s useful to know, however, is that you can add a third property called attribute:
attributeMap : {
variable : {
node : 'myNode',
type : 'attribute',
attribute : 'alt'
}
},
In this example, variable will be mapped to the alt property of myNode. Very useful if you want to set a src on 2 separate images, for example.