Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
drublic committed Dec 22, 2014
0 parents commit c874b89
Show file tree
Hide file tree
Showing 8 changed files with 345 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules/
6 changes: 6 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
language: node_js
node_js:
- "0.10"
cache:
directories:
- node_modules
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2014 Hans Christian Reinl

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
68 changes: 68 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Templates - vanilla-templates

[![Build Status](https://api.travis-ci.org/drublic/Templates.svg)](http://travis-ci.org/drublic/Templates)

Template parsing with jQuery and Hogan


You can read more about Hogan and Mustache here:

* Hogan: http://twitter.github.io/hogan.js/
* Mustache: http://mustache.github.io/

## Usage

Templates with the attribute `x-template` get indexed by their name and
injected into the DOM where the attribute `x-template-inject` matches the
template's name.

To inject a specific template you can call
`Templates.inject(templatename, data)` while `templatename` is the value of
`x-template` and `data` is the object or array of objects that holds the data
to be passed to the Hogan template.

## Example

Here is an example template:

<script x-template="foobar">
<h1>{{title}}</h1>
</script>

You would need an element where your temptate should be injected with data:

<div x-template-inject="foobar"></div>

In JS you would now call the template with the according data:

Templates.inject('foobar', {
title: 'This was fun!'
});

This reneders in HTML as:

<div x-template-id="foobar__08a2341b"><h1>This was fun!</h1></div>

and is injected at the point where you defined `x-template-inject="foobar"`.
The ID is generated automatically but you can also define manual IDs by setting
`id` on each object you inject.

Templates.inject('foobar', {
title: 'This was fun!',
id: 'title-element'
});


The generated ID will be stored on each object

If you want to you can now update the data like this:

Templates.update('foobar', 'title-element' {
title: 'This is even more fun!',
id: 'title-element'
});

### Why?

Most of the time you need some kind of system around building templates and
injecting them. This plugin enables you to do so with a couple of conventions.
123 changes: 123 additions & 0 deletions Templates.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/**
* TEMPLATES
* Template parsing with jQuery and Hogan
*
* Hogan: http://twitter.github.io/hogan.js/
* Mustache: http://mustache.github.io/
*
* Templates with `x-template` get indexed by their name and injected into the
* DOM where `x-template-inject` matches the template's name.
*
* To inject a specific template you can call
* `Templates.inject(templatename, data)` while `templatename` is the value of
* `x-template` and data is the object that holds the data to be passed to
* the Hogan template.
*/
void function (global, $, Hogan) {

var Templates = {};

/**
* All templates on a page
* @return {jQuery Object} All templates on a page
*/
Templates.getTemplates = function () {
return $('[x-template]');
};

/**
* Get a specific template
* @param {String} page
* @return {jQuery Object} Template
*/
Templates.get = function (page) {
return Templates.getTemplates().filter('[x-template~="' + page + '"]').html();
};

/**
* Parse templates and render them with data
* @param {Sting} template HTML of template
* @param {Object} data Data to inject into template
* @return {String} Parsed template
*/
Templates.parse = function (template, data) {
var parsedTemplate = Hogan.compile(template);

return parsedTemplate.render(data);
};

/**
* Generate UUID
* @return {String}
*/
Templates.generateId = function () {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1) +
Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
};

/**
* Inject templates where they are needed
* @param {String} templateName Name of template
* @param {Object} data Data to inject into template
* @return {void}
*/
Templates.inject = function (templateName, data) {
var template = Templates.get(templateName);
var html = '';
var i = 0;

// If data is not provided as an array
if (!$.isArray(data)) {
data = [data];
}

for (; i < data.length; i++) {
data[i].name = data[i].name || Templates.generateId();
data[i].id = templateName + '__' + data[i].name;

html += '<div x-template-id="' + data[i].id + '">' + Templates.parse(template, data[i]) + '</div>';
}

$('[x-template-inject~="' + templateName + '"]').html(html);
};

/**
* Update a given template
* @param {String} templateName Name of template
* @param {String} name ID of element to update
* @param {Object} data Data to inject into template
* @return {void}
*/
Templates.update = function (templateName, name, data) {
var template = Templates.get(templateName);
var html = Templates.parse(template, data);

// Replace element with new element
$('[x-template-id="' + templateName + '__' + name + '"]')
.after(html)
.remove();
};

/*
* AMD, module loader, global registration
*/

// Expose loaders that implement the Node module pattern.
if (typeof module === 'object' && module && typeof module.exports === 'object') {
module.exports = Templates;

// Register as an AMD module
} else if (typeof define === 'function' && define.amd) {
define('Templates', ['jQuery', 'Hogan'], function () {
return Templates;
});

// Export into global space
} else if (typeof global === 'object' && typeof global.document === 'object') {
global.Templates = Templates;
}
}(this, jQuery, Hogan);
18 changes: 18 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "vanilla-templates",
"version": "1.0.0",
"description": "",
"main": "Templates.js",
"author": "Hans Christian Reinl <[email protected]> (https://drublic.de/)",
"scripts": {
"test": "jasmine"
},
"devDependencies": {
"jasmine": "^2.1.1",
"jsdom": "^1.5.0"
},
"dependencies": {
"hogan.js": "^3.0.2",
"jquery": "^2.1.3"
}
}
99 changes: 99 additions & 0 deletions spec/Templates.Spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/**
* Test specification for Templates
*
* Tests with Jasmine
*/

// Create a DOM
var jsdom = require('jsdom');

// Add dependencies
global.jQuery = require('jquery')(jsdom.jsdom().parentWindow);
global.Hogan = require('hogan.js');

$ = jQuery;

// Load module
var Templates = require('../Templates');

describe('Templates', function () {
beforeEach(function () {
$('body')
.append('<div x-template="test">{{name}}</div>')
.append('<div x-template-inject="test"></div>');
});

afterEach(function () {
$('[x-template], [x-template-inject]').remove();
});

it('exisits', function () {
expect(Templates).not.toBe(undefined);
});

it('finds all templates', function () {
expect(Templates.getTemplates().length).toBe(1);
expect(Templates.getTemplates().first().html()).toBe('{{name}}');
});

it('parses templates', function () {
var template = Templates.parse('{{foo}}', {
foo: 'foo'
});

var template2 = Templates.parse('{{foo}} {{bar}}', {
foo: 'foo',
bar: 'bar'
});

expect(template).toBe('foo');
expect(template2).toBe('foo bar');
});

it('generates unique IDs', function () {
expect(Templates.generateId().length).toBe(8);
});

it('injects templates with data as object', function () {
Templates.inject('test', {
name: 'foo'
});

expect($('[x-template-inject="test"]').text()).toBe('foo');
});

it('injects templates with id set', function () {
Templates.inject('test', {
name: 'foo',
id: 'foobar'
});

expect($('[x-template-inject="test"]').text()).toBe('foo');
});

it('injects templates with data as array', function () {
Templates.inject('test', [{
name: 'foo'
}, {
name: 'bar'
}]);

expect($('[x-template-inject="test"]').text()).toBe('foobar');
});

it('updates template with data as object', function () {
Templates.inject('test', {
name: 'foo',
id: 'foo'
});

expect($('[x-template-inject="test"]').text()).toBe('foo');

Templates.update('test', 'foo', {
name: 'bar',
id: 'foo'
});

expect($('[x-template-inject="test"]').text()).toBe('bar');
});
});
9 changes: 9 additions & 0 deletions spec/support/jasmine.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"spec_dir": "spec",
"spec_files": [
"**/*[sS]pec.js"
],
"helpers": [
"helper.js"
]
}

0 comments on commit c874b89

Please sign in to comment.