Jacobian
Jacobian

Reputation: 10812

How to set custom component template and pass template arguments?

I want to create a custom component with some custom template. And I want this template to have some arguments. Now my code looks like so:

    Ext.define('Ext.ux.TestComponent', {
        extend:'Ext.Component',
        alias: 'widget.testcomponent', 
        requires: [
            'Ext.XTemplate'
        ],
        constructor: function(config) {
            Ext.applyIf(config, {
                tpl: [
                    '<div class="custom_cls" custom_attr="{custom_attr_value}">Hello world</div>',
                    {compiled: true}
                ]
            });
            this.callParent([config]);
        }
    });

    Ext.create("Ext.ux.TestComponent",{
        renderTo: document.getElementById("component")
    });

Here is a fiddle with this code. The first problem with this code is that my custom template is not rendered at all. The second problem, is that I do not know how to pass arguments to this template (and to set custom_attr in my example). When I extend Button, for example, I know I can use renderTpl and getTemplateArgs() and when I extend DataView, I can configure the template inside the constructor. But all this just does not work, when I extend Component. So, what is wrong with that and how can I fix it?

Upvotes: 0

Views: 1111

Answers (2)

Evan Trimboli
Evan Trimboli

Reputation: 30082

tpl is used in conjunction with the data config.

Ext.define('Ext.ux.TestComponent', {
    extend: 'Ext.Component',

    tpl: [
        '<div class="custom_cls" custom_attr="{custom_attr_value}">{content}</div>'
    ]
});

Ext.create("Ext.ux.TestComponent", {
    renderTo: document.body,
    data: {
        custom_attr: 'x',
        content: 'y'
    }
});

Upvotes: 2

Artem Stepin
Artem Stepin

Reputation: 421

You need to define your template within the renderTpl configuration.
Additional data can be applied via renderData.

Ext.define('Ext.ux.TestComponent', {
    extend: 'Ext.Component',
    renderTpl: [
        '<div class="custom_cls" custom_attr="{custom_attr_value}">Hello</div>'
    ],
    renderData: {
        custom_attr_value: "TestValue"
    }
});

Here is the full example:
https://fiddle.sencha.com/#view/editor&fiddle/21eg


As an alternative to handing over the renderData object, you can implement an initRenderData function in your component. This function is called by the mixin Ext.util.Renderable, which is used by Ext.Component.

Ext.define('Ext.ux.TestComponent', {
    extend: 'Ext.Component',
    renderTpl: [
        '<div>{title}</div>'
    ],

    config: {
        title: 'default',
    },

    initRenderData() {
        return this;
    },
});

Ext.create("Ext.ux.TestComponent", {
    renderTo: Ext.getBody(),
    title: 'TestTitle'
});

Here is my full example for this alternative solution:
https://fiddle.sencha.com/#view/editor&fiddle/21en

Upvotes: 2

Related Questions