Notice: The Monaca & Onsen UI Community Forum is shutting down.

For Onsen UI bug reports, feature requests and questions, please use the Onsen UI GitHub issues page. For help with Monaca, please contact Monaca Support Team.

Thank you to all our community for your contributions to the forum. We look forward to hearing from you in the new communication channels.

Load page from one template and add content from another template



  • Hello,

    I would like to reuse a template containing an ons-page and an ons-toolbar, rather than putting the same ons-toolbar code into every html page.
    Is that possible?

    I have this template in a separate html file:

    <ons-page id="pageTemplate">
        <ons-toolbar fixed-style>
            <div class="left appDefaultColors">
                <ons-toolbar-button onclick="App.showMenu()">
                    <ons-icon icon="md-menu"></ons-icon>
                </ons-toolbar-button>
            </div>
            <div id="pageTitle" class="center appDefaultColors bold">AppTitle</div>
        </ons-toolbar>
        <div id="contentFromTemplate">Content from another template here.</div>
    </ons-page>
    

    I load the page in an <ons-splitter/> like this:

    var content = document.getElementById('content');
    var menu = document.getElementById('menu');
    content.load("pageTemplate.html")
          .then(menu.close.bind(menu));
    

    I would like to set the innerHTML of the “contentFromTemplate” div - or use some other method to dynamically add content.
    It seems to me that the easiest way would be to change the ons-page id at this point. Then I could handle everything else on the init event.
    I tried

    var content = document.querySelector('ons-splitter-content')
    

    right after content.load. But the content has still the old page content at this point.

    How can I get a handle on the page which has just been loaded? Or is my approach completely wrong and I should use a different pattern?

    Thanks for any help!


  • administrators

    Are you not able to get a reference to the loaded content in the callback promise from content.load?

    content.load("pageTemplate.html")
          .then(              // <----- can you get a reference to the content in here?
          );
    

    What is document.querySelector returning if you call it in the promise callback?



  • @emccorson
    Thanks a lot, you are right, I used the promise wrong.
    For others who have the same problem, here is how it looks for me now:

    var content = document.getElementById('content');
    var menu = document.getElementById('menu');
    content.load("pageTemplate.html")
    .then(function() {
    var page = document.querySelector('ons-splitter-content').lastChild;
    page.setAttribute('mode','firstpage'); //this is used to know which content should be filled into the template.
    menu.close();
    });
    

    That works for me. Thank you!