Monaca Onsen UI Discord Chat Github Repo

Newbie Question about templates



  • What is the point of templates? In reading the docs I thought they were like includes that would pull information from external files. But they don’t work that way as far as I can tell from building the getting started sample. It looks like all of the HTML and javascript code all have to be on the one page. If I take the contents of the sample <template id=page1.html> and put it into a page1.html file, I get javascript errors about it not finding the elements I just moved to the external file.

    onsenui.min.js:2 Uncaught (in promise) TypeError: Cannot read property 'remove' of undefined
        at Object.Q.createElement (onsenui.min.js:2)
        at onsenui.min.js:2
    

    So I don’t understand why the template IDs have to be real pages. Or why would a template would be used instead of using ons-page.

    Can someone help me understand templates?


  • administrators

    Templates are fragments of HTML that are not rendered immediately when a page is loaded, but can be rendered later. This is useful for speeding up loading times because templates don’t need to be rendered when the app starts. For example, if your app contains a page in a template and the user never visits that page, the page will never be rendered. If you hadn’t used a template, the page would have been rendered even though the user never visited it.
    https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template

    In Onsen UI, there are two ways of defining pages that the navigator can load. One is by using the template tags e.g.:

    <template>
      <ons-page>...</ons-page>
    </template>
    

    The other way is to define a page in a separate file (without the template tags).

    A template isn’t used instead of ons-page. ons-page defines an Onsen UI page; template lets the browser know that it shouldn’t be loaded at startup.

    I hope that helps. If you still have questions please let us know.