1

I am using a framework called Framework7.

In my index.html, I have some Template7 code, like this format

<script type="text/template7" id="commentsTemplate">
    {{#each this}}
    <div> test this template 7 code </div>
</script>

However, I want to have this part of code into an another separated file (Just like I can have many other *.js files in, say, a static folder and refer to the file by "static/*.js).

I have tried to use a typical way to import js

<script type="text/template7" id="storiesTemplate" src="js/template.js"></script>

But it doesn't work, there is also no demo/sample code in the documentation.

Any help is appreciated!

SonicC
  • 13
  • 4

3 Answers3

0

You can do it. The idea behind is to include a HTML file in a HTML file. I can tell at least 3 ways that this can happen, but personally I fully validated only the third.

  • First there is a jQuery next sample is taken from this thread

    a.html:

       <html> 
       <head> 
            <script src="jquery.js"></script> 
            <script> 
                $(function(){
                    $("#includedContent").load("b.html"); 
                });
            </script> 
       </head> 
       <body> 
            <div id="includedContent"></div>
       </body> 
       </html>
    

    b.html:

    <p> This is my include file </p>
    
  • Another solution, I found here and doesn't require jQuery but still it's not tested: there is a small function

  • My solution is a pure HTML5 and is probably not supported in the old browsers, but I don't care for them.

Add in the head of your html, link to your html with template

    <link rel="import" href="html/templates/Hello.html">

Add your template code in Hello.html. Than use this utility function:

    loadTemplate: function(templateName)
    {
        var link = document.querySelector('link[rel="import"][href="html/templates/' + templateName + '.html"]');
        var content = link.import;
        var script = content.querySelector('script').innerHTML || content.querySelector('script').innerText;
        return script;
    }

Finally, call the function where you need it:

    var tpl = mobileUtils.loadTemplate('hello');
    this.templates.compiledTpl = Template7.compile(tpl);

Now you have compiled template ready to be used.

=======UPDATE

After building my project for ios I found out that link import is not supported from all browsers yet and I failed to make it work on iphone. So I tried method number 2. It works but as you might see it makes get requests, which I didn't like. jquery load seems to have the same deficiency.

So I came out with method number 4.

<iframe id="iFrameId" src="html/templates/template1.html" style="display:none"></iframe>

and now my loadTemplate function is

loadTemplate: function(iframeId, id)
{
    var iFrame = document.getElementById(iframeId);
    if ( !iFrame || !iFrame.contentDocument ) {
        console.log('missing iframe or iframe can not be retrieved ' + iframeId);
        return "";
    }

    var el = iFrame.contentDocument.getElementById(id);
    if ( !el ) {
        console.log('iframe element can not be located ' + id );
        return "";
    }

    return el.innerText || el.innerHTML;
}
Community
  • 1
  • 1
user732456
  • 2,638
  • 2
  • 35
  • 49
0

How about lazy loading and inserting through the prescriptions?

    (function (Template7) {
    "use strict";
    window.templater = new function(){
        var cache = {};

        var self = this;

        this.load = function(url)
        {
            return new Promise(function(resolve,reject)
            {
                if(cache[url]){
                    resolve(cache[url]);
                    return true;
                }

                if(url in Template7.templates){
                    resolve(Template7.templates[url]);
                    return true;
                }

                var xhr = new XMLHttpRequest();
                xhr.open('GET', url);
                xhr.onload = function() {
                    if(this.status == 200 && this.response.search('<!DOCTYPE html>') == -1){
                        cache[url] = Template7.compile(this.response);
                        resolve(cache[url]);
                    }else{
                        reject(`Template ${url} not found`);
                    }
                };
                xhr.send();
            })
        }

        this.render = function(url, data)
        {
            return self.load(url)
                .then(function(tpl){
                    return tpl(data) ;
                });
        } 

        this.getCache = function()
        {
            return cache;
        }

    }
})(Template7);

Using :

templater.render('tpl.html').then((res)=>{ //res string })

Or :

templater.load('tpl.html').then( tpl => { Dom7('.selector').html( tpl(data) ) } )
gmuraleekrishna
  • 3,375
  • 1
  • 27
  • 45
-1

It is possible to define your templates in .js-files. The template just needs to be a string. Refer to this [JSFiddle] (https://jsfiddle.net/timverwaal/hxetm9rc/) and note the difference between 'template1' and 'template2'

var template1 = $$('#template').html();
var template2 = '<p>Hello, my name is still {{firstName}} {{lastName}}</p>'

template1 just extracts the content of the <script> and puts it in a string. template2 directly defines the string

Tim V
  • 490
  • 3
  • 8
  • Does it mean that it's impossible or hard to have those template code as html format in another .html file? – SonicC Jul 28 '16 at 01:39
  • Have you considered using server-side coding for this? With, for example, PHP it is possible to put the HTML-code in separate PHP-files. We this approach you can have both, (1) the templates in HTML format and (2) separate files for you templates... – Tim V Jul 28 '16 at 09:59