-
Notifications
You must be signed in to change notification settings - Fork 4
HTML Templating
There are several possibilities to implement a html-template for a ccm-component.
A common way to implement html-templates in ccm is to include JSON-formatted tag-definitions in a config-file.
ccm.component.js
var component = {
config: {
html1: {
"tag": "div",
"class": "card",
"inner": [
{
"tag": "img",
"class": "card-img-top",
"src": "%img_src%",
"alt": "%img_alt%"
},
{
"tag": "div",
"class": "card-body",
"inner": [
{
"tag": "h5",
"class": "card-title",
"inner": "%title%"
},
{
"tag": "p",
"class": "card-text",
"inner": "%text%"
}
]
}
]
}
},
Instance: function () {
this.start = callback => {
const html1 = this.ccm.helper.html( this.html1, {
img_src: 'https://ccmjs.github.io/ccm/unit_tests/dummy/image.png',
img_alt: 'my value for alt attribute',
title: 'my card title',
text: 'text of my card'
} );
this.element.appendChild( html1 );
callback && callback();
};
}
};
To make a config-file more readable or to make the templating more interchangeable, the definition can be outsourced in a separate js-file.
ccm.component.js
var component = {
config: {
html2: [ 'ccm.load', 'tpl.card.js' ]
},
Instance: function () {
this.start = callback => {
const html2 = this.ccm.helper.html( this.html2, {
img_src: 'https://ccmjs.github.io/ccm/unit_tests/dummy/image.png',
img_alt: 'my value for alt attribute',
title: 'my card title',
text: 'text of my card'
} );
this.element.appendChild( html2 );
callback && callback();
};
}
};
tpl.card.js
ccm.files[ 'tpl.card.js' ] = {
"tag": "div",
"class": "card",
"inner": [
{
"tag": "img",
"class": "card-img-top",
"src": "%img_src%",
"alt": "%img_alt%"
},
{
"tag": "div",
"class": "card-body",
"inner": [
{
"tag": "h5",
"class": "card-title",
"inner": "%title%"
},
{
"tag": "p",
"class": "card-text",
"inner": "%text%"
}
]
}
]
};
Last but not least there is a way to import html-files in ccm. This variant is a good solution for beginners who already know html.
ccm.component.js
var component = {
config: {
html3: [ 'ccm.load', 'tpl.card.html' ]
},
Instance: function () {
this.start = callback => {
const html3 = this.html3
.replace( '{{img_src}}', 'https://ccmjs.github.io/ccm/unit_tests/dummy/image.png' )
.replace( '{{img_alt}}', 'my value for alt attribute' )
.replace( '{{title}}' , 'my card title' )
.replace( '{{text}}' , 'text of my card' );
this.element.innerHTML += html3;
callback && callback();
};
}
};
tpl.card.html
<div class="card">
<img class="card-img-top" src="{{img_src}}" alt="{{img_alt}}">
<div class="card-body">
<h5 class="card-title">{{title}}</h5>
<p class="card-text">{{text}}</p>
</div>
</div>
From ccm v17 the result when loading an HTML file is then no longer a string, but a document element, in which you can select and work as usual with querySelectorAll () and the like. The placeholder would have to be replaced but also by hand.