erotavlas
erotavlas

Reputation: 4493

How to set template string dynamically?

In Dojo 1.10+ is there a way to set the templateString of a template based widget dynamically?

For example I tried something like this

...
return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], {

templateString: undefined,

constructor: function(myTemplate){
    var that = this;

    //set the template
    require(["dojo/text!" + myTemplate], function (template) {
        that.templateString = template;
    });
}
...

but it was unsuccessful, templateString is always undefined so it crashes with a 404 error because it can't find the html file.

Is this even possible?

Upvotes: 0

Views: 1004

Answers (1)

pgianna
pgianna

Reputation: 725

If there is only a limited set of templates that may be set you can use something like this:

define([
    "dojo/_base/declare",
    "dijit/_TemplatedMixin",
    "dojo/text!path_to_template1.html",
    "dojo/text!path_to_template2.html"
], function(declare, _TemplatedMixin, template1, template2)
{
    return declare([_TemplatedMixin],
    {
        templateToUse: 1,

        constructor: function(params)
        {
            this.templateToUse = params.templateToUse;
        },

        buildRendering: function()
        {
            switch(this.templateToUse) {
                case 2:
                    this.templateString = template2;
                    break;
                case 1:
                    this.templateString = template1;
                    break;
                default:
                    this.templateString = template1;
            };

            this.inherited(arguments);
        }
    }
}

I have to ask what is the use case for this because I can see several alternatives that are potentially better.

  • If the templates are significantly different why not create separate widgets? You can use OOP or mixin techniques that dojo offers to share functionality between them.
  • A single template can be highly customized with parameters passed to the widget constructor. You can attach different elements to dojo attach points or even hide some elements by setting the display:none style to them.

Upvotes: 3

Related Questions