Framework7 - Auto Compilation



Description

In Template7 you can compile your templates automatically by specifying special attributes in a <script> tag.

The following code shows the auto compilation layout −

<script type = "text/template7" id = "myTemplate">
   <p>Hello, my name is {{name}} and i am {{age}} years old</p>
</script> 

You can use the following attributes for initializing the auto compilation −

  • type = "text/template7" − It is used to tell Template7 to auto compile and it is a required script type.

  • id = "myTemplate" − Template is accessible through the id and it is a required template id.

For automatic compilation, you need to enable app initialization by passing the following parameter −

var myApp = new Framework7 ({
   //It is used to compile templates on app init in Framework7
   precompileTemplates: true,
});

Template7.templates / myApp.templates

The automatically compiled templates can be accessed as properties of Template7.templates after initializing the app. It is also known as myApp.templates where myApp is an initialized instance of the app.

You can use the following templates in our index.html file −

<script type = "text/template7" id = "personTemplate">
   <p>Hello, my name is {{name}} and i am {{age}} years old</p>
   <p>I work as {{position}} at {{company}}</p>
</script>
 
<script type = "text/template7" id = "carTemplate">
   <p>I have a great car, it is {{vendor}} {{model}}, made in {{year}} year.</p>
   <p>It has {{power}} hp engine with {{speed}} km/h maximum speed.</p>
</script> 

You can also access templates in JavaScript after app initialization −

var myApp = new Framework7 ({
   //Tell Framework7 to compile templates on app init
    precompileTemplates: true
});
 
// Render person template to HTML, its template is already compiled and accessible as 
//Template7.templates.personTemplate
var personHTML = Template7.templates.personTemplate ({
   name: 'King Amit',
   age: 27,
   position: 'Developer',
   company: 'AngularJs'
});
 
// Compile car template to HTML, its template is already compiled and accessible as 
//Template7.templates.carTemplate
var carHTML = Template7.templates.carTemplate({
   vendor: 'Honda',
   model: 'city',
   power: 1200hp,
   speed: 300
});
Advertisements