# $.template `$.template()` renders HTML templates with JavaScript mixed inside them. Example: ```html ``` renders all `script[type="text/html"]` as [lodash templates](https://lodash.com/docs/#template). This displays `Your platform is ...` and shows the userAgent just below the script tag. - Anything inside `<% ... %>` is executed as Javascript. - Anything inside `<%= ... %>` is evaluated and rendered in-place. The template can use all global variables. You can pass additional variables using as `.template({var1: value, var2: value, ...})`. For example: ```html ``` To re-render the template, run `.template(data)` again with different data. ## $.template animation When using `type="text/html"`, templates are re-rendered. To *update* existing elements, use `data-engine="vdom"` instead. This only changes attributes or elements that need change. This allows us to animate attributes via CSS. You need to include [morphdom](https://github.com/patrick-steele-idem/morphdom) for this to work. For example, this shows a circle in SVG bouncing around smoothly. ```html ``` You can also specify a `data-engine` via an option. For example: ```js $('script.animate').template(data, {engine: 'vdom'}) ``` ## $.template targets To re-use the template or render the same template on a different DOM node, run `.template(data, {target: selector})`. This allows you to declare templates once and apply them across the body. For example: ```html
``` The target can also be specified via a `data-target=".panel1"` on the script template. This is the same as specifying `{target: '.panel'}`. For example: ```html ``` ## $.template append To append instead of replacing, use `data-append="true"`. Every time `.template` is called, it appends rather than replaces. For example: ```html ``` You can also specify this as `.template(data, {append: true})`. You can also append to an [existing target](#template-targets). For example: ```html ``` ## $.template external source Template containers can have an `src=` attribute that loads the template from a file: ```html ``` If the `src=` URL returns a HTTP error, the HTML *inside* the script is rendered as a template. The template can use: - all data passed by the `$().template()` function, and - an [xhr](http://api.jquery.com/Types/#jqXHR) object - which has error details. For example: ```html ``` ## $.template selector `$(...).template()` renders all `script[type="text/html"]` nodes in or under the selected node. Use `data-selector=` attribute to change the selector. For example: ```html
``` You can also use the `selector: ...` option. For example: ```html
``` ## $.template events - `template` is fired on the source when the template is rendered. Attributes: - `templatedata`: the passed data - `target`: the target nodes rendered, as a jQuery object For example: ```html ```