Template association in a page


#1

For a given page (js/xml/css) is it possible to dynamically inject another template o part of it (in the form of a string) in place of the one normally defined in page.xml that is associated by default?


#2

I guess you are asking about building reusable custom components. Checkout the docs here.


#3

Hi @manojdcoder, let me explain you.

Actually in xml templates I did not found constructs for dynamic generation. It would be great to have thing like Handlebars template engine. Trivial example:

{{#if imageUrl}}
    <Image src={{ image }} ..../>
    <Label text="{{ title }}" .... />
{{else}}
    <Label text="{{ title }}" .... />
{{/if}}

and so on… (as you probably know Handlebars has a lot of constructs and extensibility mechanism, it is very powerful and fast).

Note: in the case above I could use visibility, but both sections are built anyway, and this is a problem for efficiency and even consistency (image==null -> crash).

So I’was thinking: if for a page, o part of it, there is a way to inject the template (xml string) before it is used by {N} to compute the page, I could generate on the fly the template through Handlebars (basing on a separate data context or the bindingContext) that produces the clean template ready to use (which still have the binding variables) and the trick is done!

I tried to run Handlebars inside a {N} page and it works (see code below), but I have no idea if it is possible to put it as the xml content.

function onNavigatingTo(args) {
    const page = args.object;
    page.bindingContext = new CustomerViewModel();

    var source = ' <Page navigatingTo="onNavigatingTo" class="page" xmlns="http://schemas.nativescript.org/tns.xsd" > \
    <ActionBar class="action-bar"> \
        <Label class="action-bar-title" text="Home"></Label> \
    </ActionBar> \
    <Label text="{{ message }}"></Label> \
    </Page> ';

    var data = { // This data is in general independent form the bindingContext
        "message": "This is generate by Handlebars!!!!"
    };
    var template = Handlebars.compile(source);
    var result = template(data);

    console.log(result);

    // Now... how to set the generated page??
}

#4

No, such advanced templating are not supported in NS Core which is why I mostly prefer Angular for development.

And sorry I never used Handlebars.


#5

In fact, probably at this point I have to consider Angular or Vue.

Thanx!