Giter VIP home page Giter VIP logo

jquery-mustache's Introduction

jQuery-Mustache - A jQuery Plugin for working with Mustache.js

jQuery-Mustache.js is a jQuery Plugin which makes working light work of using the Mustache templating engine via a bit of jQuery magic.

Installation

jQuery-Mustache has two dependencies:

As with all jQuery plugins, just ensure that you load jQuery before you load jQuery-mustache.js, for example:

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script>
<script src="https://raw.github.com/jonnyreeves/jquery-Mustache/master/jquery.mustache.js"></script>
<script src="https://raw.github.com/janl/mustache.js/master/mustache.js"></script>

Usage

Lets get down to it and load an external template and then render it.

var viewData = { name: 'Jonny' };
$.Mustache.load('./templates/greetings.htm')
	.done(function () {
    	$('body').mustache('simple-hello', viewData);
    });

In the above example we are loading an external template HTML file (greetings.htm) and, once it's finished loading we render it out replacing the contents of the body element. Your templates should be defined in a script block in the external HTML file where the script block's id will define the template's name, eg:

<script id="simple-hello" type="text/html">
    <p>Hello, {{name}}, how are you?</p>
</script>

You can also add templates directly either as String literals or by referencing other DOM elements, eg:

$.Mustache.add('string-template', '<p>Hi, {{name}}, this is an inline template<p>');

// These two are identical, the latter just provides a terser syntax.
$.Mustache.add('dom-template', $('#dom-template').html());
$.Mustache.addFromDom('dom-template');

If you prefer to have all your templates stored in the DOM (as opposed to loading them from external files) then you can just call $.Mustache.addFromDom() without any arguments, this will read in all templates from any <script type="text/html" /> blocks in your markup.

There are two ways to render a Mustache template, either via the global $.Mustache.render() method or via the jQuery mustache selector:

$.Mustache.render('my-template', viewData);		// Returns a String (the rendered template content)
$('#someElement').mustache('my-template', viewData);	// Returns a jQuery selector for chaining.

The jQuery mustache selector defaults to appending the rendered template to the selected element; however you can change this behaviour by passing a method in the options argument:

// Replace the contents of #someElement with the rendered template.
$('#someElement').mustache('my-template', viewData, { method: 'html' });

// Prepend the rendered Mustache template to #someElement.
$('#someElement').mustache('my-template', viewData, { method: 'prepend' });

The mustache selector also allows you to pass an Array of View Models to render which makes populating lists a breeze:

// Clear #someList and then render all the viewModels using the list-template.
$('#someList).empty().mustache('list-template', viewModels);

To help you debug you can fetch a list of all registered templates via $.Mustache.templates() and when you're done, you can call $.Mustache.clear() to remove all templates.

jQuery-Mustache plays nicely with partials as well, no muss, no fuss, just drop the partial into your template, ensure that it's been loaded and jQuery-Mustache will take care of the rest:

<!-- Templates.htm -->
<script id="footer-fragment" type="text/html">
	<p>&copy; Jonny {{year}}</p>
</script>
<script id="webcontent" type="text/html">
	<h1><blink>My {{adjective}} WebSite!</blink></h1>
	
	{{! Insert the `footer-fragment` template below }}
	{{>footer-fragment}}
</script>

$.Mustache.load('templates.htm')
	.done(function () {
		// Renders the `webcontent` template and the `footer-fragment` template to the page.
		$('body').mustache('webcontent', { year: 2012, adjective: 'EPIC' }); 
	});

Check out the included example file for other usage scenarios.

jquery-mustache's People

Contributors

jakul avatar jbbrunsveld avatar jonnyreeves avatar loadedsith avatar rickysullivan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery-mustache's Issues

html is rendered as text

Hi

I use the code below to render mark-up for my Preview element.

$('#Preview).mustache('my-template', viewData, { method: 'html' });

The viewData contains fields that contain raw text as well as fields which contain html markup. The problem is that the html markup is not rendered, so instead of showing for instance Hello World in bold the Preview element shows <b>Hello World</b>
Is this a bug or am I doing something wrong?

Thanks
Peter

jquery-Mustache and requireJS (AMD)

Since few months mustache.js have a specific jQuery wrapper. But it focuses on wrapping Mustache.render(). jquery-Mustache seems to have a much broader scope (especially $.Mustache.load that I used to preload templates).

So i tried to add jquery-mustache in my requireJS config, but i'm not able to have a correct configuration.

require.config({
    baseUrl: 'js/libs',
    urlArgs: "c=" + (new Date()).getTime(),
    shim: {
        'jquery-mustache': {
            deps: ['jquery', 'mustache']
        }
    },
    paths: {
      'jquery': "jquery/dist/jquery",
      'mustache': "mustache/mustache",
      'jquery-mustache': "jquery-Mustache/jquery.mustache",
      'requirejs': "requirejs/require"
    }
});

But jquery-Mustache doesn't find window.Mustache object

Do you have any clue ?

addFromDom() only gets templates from the body

The docs say the templates can be stored anywhere in the DOM and addFromDom() will get all of them, but they're only pulled from the body. Suggest clearer language in the documentation or changing the jquery selector to $("script") rather than $("body script").

How to Use Parse?

$.Mustache.load('./templates/template.htm')
.done(function () {
var customTags = [ '@@', '@@)' ];
$.Mustache.parse(this, customTags); // <=============== fails
console.log($.Mustache);

$.Mustache.tags = customTags;
// Subsequent parse() and render() calls will use customTags

$.Mustache.options.warnOnMissingTemplates = true;
                    
$.Mustache.parse(template);   // optional, speeds up future uses <============ fails
$('body').mustache('mypage', view);

});

Uncaught TypeError: $.Mustache.parse is not a function
at Object. (test.html:103)
at i (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at A (jquery.min.js:4)
at XMLHttpRequest. (jquery.min.js:4)

Thank you.

'load' does not work if there is only one 'script' tag

It looks like if the template has only one script tag with a template it does not load the template.

I think it's because it load the content of the script but not the tag itself with the content and the filter("script") does not work.

One solution (or hack) would be to ask check tagName in the data received. If it's 'undefined' then it's only one tag.

window.Mustache is not set?

Sorry for all the n00b comments...

I have some simple code that looks like this:

$(document).ready(function(){
    $.Mustache.load('templates.html', function(){
        console.log('templates loaded');
        init();
    });
});

The load works, and if I add a console.log in the add method I can see that my templates have been found correctly in the HTML template file.

However, when I later run $('#my-id').mustache('my-template', {}) I get an error in the JS console:

Uncaught Error: Failed to locate Mustache instance, are you sure it has been loaded?

From what I can see, this is occurring because getMustache is looking for window.Mustache but it looks like that's never set. Should it instead be $.Mustache?

I'm not completely sure what I'm doing here, so this might be pilot error...

Getting a 404 despite having the right path, why?

The following setup gets a jQuery plugin mixitup working perfectly.

"browser": {
        "mixitup": "./app/bower_components/mixitup/src/jquery.mixitup.js",
        "jquerymustache": "./app/bower_components/jquery-Mustache/src/jquery.mustache.js"
    },
    "browserify": {
        "transform": [
            "browserify-shim"
        ]
    },
    "browserify-shim": {
        "mixitup": {
            "exports": "mixitup",
            "depends": [
                "jquery:jQuery"
            ]
        },
        "jquerymustache": {
            "exports": "Jquerymustache",
            "depends": [
                "jquery:jQuery",
                "mustache:mustache"
            ]
        }
    },

However, when I try to apply the same convention to jquery-Mustache, I am not able to get my templates fetch:

 "browser": {
   "jquerymustache": "./app/bower_components/jquery-Mustache/src/jquery.mustache.js"
  }

and

"jquerymustache": {
      "exports": "Jquerymustache",
      "depends": [
        "jquery:jQuery",
        "mustache:mustache"
      ]
    }

I don't get an error from the terminal, (that would prove the package.json setup is kosher) but I do get this error from the console:

enter image description here

Which points to this:

enter image description here

This is my app.js file, feel this is the most relevant information:

var $ = jQuery = require('jquery');
var mixitup = require('mixitup');
var Jquerymustache = require('jquerymustache');
var mustache = require('mustache');

And the function which is fetching the template.

function templateLoader(e) {
        var doc = document,
            event = EventUtility.getEvent(e),
            target = EventUtility.getTarget(event);
        $.Mustache.options.warnOnMissingTemplates = true;

        $.Mustache.load('templates/index.html')
            .fail(function() {
                $('#overlay').append('Failed to load templates from <code>templates.htm</code>');
            })
            .done(function() {
                var output = $('#overlay');
                $('body').mustache('templateID');
            });
    }

And the file path for good measure, to prove the path in the function is correct:

enter image description here

Add AMD support

I'm using RequireJS it works fine with Mustache and JQuery (latest versions), but not with jquery-Mustache. Can you add support for AMD ?

Options.method ambiguous and dangerous

Right now the $.fn.mustache function allows you to pass in the name of the jquery method you want it to call. It defaults to append. In my particular use case I wanted it to replace rather than append. The resultant call looked like this:

$('#users').mustache('users_template', data, {method:'html'});

A couple reasons why this call rubs me the wrong way:

  1. I had to go read the source code to know what I needed to do
  2. You open yourself up to problems if you just let the user pass in method names like that. If they pass in the wrong name, they'll get either errors if jquery doesn't have that method, or (probably even worse) unknown if jquery does have that method but it's not applicable.
  3. It's extremely confusing for those that come after me that will need to maintain it, due to the fact that it says 'html'. In most contexts, html is a content type, not a function. Which means they'll have to dig into the source code too in order to figure out what that means.

Here's my suggestion: Instead of specifying the method, specify a mode, with valid values append or replace. Then the plugin can select the jquery method appropriate for the situation. It's clear (both to current and successive users), your users no longer need to know the plugin internals, and it's more error-proof.

Just a suggestion, do with it what you will. I won't be offended either way.

Although at the very least, since there are only a handful of jquery functions that would even make sense to be passed in, (append, html, and val are the only ones I could think of off the top of my head) I'd suggest white-listing the methods that could be used and falling back on your default if they pass in a bogus one.

P.S. Also, default method/mode should be a global setting, so I don't have to change it in the source code.

[enhancement] Add missing bower.json.

Hey, maintainer(s) of jonnyreeves/jquery-Mustache!

We at VersionEye are working hard to keep up the quality of the bower's registry.

We just finished our initial analysis of the quality of the Bower.io registry:

7530 - registered packages, 224 of them doesnt exists anymore;

We analysed 7306 existing packages and 1070 of them don't have bower.json on the master branch ( that's where a Bower client pulls a data ).

Sadly, your library jonnyreeves/jquery-Mustache is one of them.

Can you spare 15 minutes to help us to make Bower better?

Just add a new file bower.json and change attributes.

{
  "name": "jonnyreeves/jquery-Mustache",
  "version": "1.0.0",
  "main": "path/to/main.css",
  "description": "please add it",
  "license": "Eclipse",
  "ignore": [
    ".jshintrc",
    "**/*.txt"
  ],
  "dependencies": {
    "<dependency_name>": "<semantic_version>",
    "<dependency_name>": "<Local_folder>",
    "<dependency_name>": "<package>"
  },
  "devDependencies": {
    "<test-framework-name>": "<version>"
  }
}

Read more about bower.json on the official spefication and nodejs semver library has great examples of proper versioning.

NB! Please validate your bower.json with jsonlint before commiting your updates.

Thank you!

Timo,
twitter: @versioneye
email: [email protected]
VersionEye - no more legacy software!

Load template file once and access templates in it several times

I am using the following code:

$.Mustache.load('/Scripts/CustomFormCreator/templates.html')
.done(function () {
$('#ControlGroupContainer').mustache('ControlGroupTemplate', controlGroup);
});

this is working great. However, I have about 4 templates within the 'templates.html' file.

I noticed that every time I call the $.Mustache.load, the file is loaded several times, which is expected.

What I wanted to do is load the 'template.html' ONCE and access all the templates with that file (from the DOM) as need.

// Load template file once (contains several defined templates)
$.Mustache.load('/Scripts/CustomFormCreator/templates.html').done();

// Load data and fill template
var html = Mustache.to_html('FirstTemplateFromLoadedFile', arrDataFoo);
$('#ArrayDataFooContainer').html(html);

And again

// Load data and fill template
var html = Mustache.to_html('SecondTemplateFromLoadedFile', arrDataBar);
$('#ArrayDataBarContainer').html(html);

Thanks ..

addFromDom() doesn't work unless a template name is specified

It seems addFromDom() isn't working for me unless I actually specify a template name. I have tried putting the template in both the HEAD tag and also the BODY tag-- it doesn't matter. The templates will only register if I actually pass in the name.

done usage of function different

var viewData = { name: 'Jonny' };
this is not work:
$.Mustache.load('./templates/greetings.htm')
.done(function () {
$('body').mustache('simple-hello', viewData);
});
});

but this worked:
$.Mustache.load('./templates/greetings.htm')
.done(myfunction());
});

unobstrusive function call not working

Hi,
I found this post of yours, thank's , very usefull for mustache beginers !

One question still :
Pre : my #tpl-greeting contain obstrusive and unobstrusive calls to javascript functions

  • if I render my template by placing the renderer - $get('greetings.html', function ... }); - within a script tag within my html main page, everything works fine,
  • but if I place the renderer in an external .js file that I integrate to my main html file right at the same place than previously, the renderer do render, but only my functions obstrusivelly called are indeed called, the ones unobstrusively called are not called anymore (while the later still works when called obstrusively) !!!

Any clues on that ?

thank's in advance

ps : I know it's not directly related to your plug-in but still is an issue for the implementation of the whole

Syntax error in the README.md

var viewData = { name: 'Jonny' };
$.Mustache.load('./templates/greetings.htm')
.done(function () {
$('body').mustache('simple-hello', viewData);
});
}); // -> this line should be removed

Failed to locate Mustache instance, are you sure it has been loaded?

Sorry for all the n00b comments...

I have some simple code that looks like this:

$(document).ready(function(){
$.Mustache.load('templates.html', function(){
console.log('templates loaded');
init();
});
});
The load works, and if I add a console.log in the add method I can see that my templates have been found correctly in the HTML template file.

However, when I later run $('#my-id').mustache('my-template', {}) I get an error in the JS console:

Uncaught Error: Failed to locate Mustache instance, are you sure it has been loaded?
From what I can see, this is occurring because getMustache is looking for window.Mustache but it looks like that's never set. Should it instead be $.Mustache?

I'm not completely sure what I'm doing here, so this might be pilot error...

Events not fire on templates elements after load - Please put it in the read.me

Events not fire on templates elements after load ...
I looked for a solution for two hours, I almost gave up the pulg-in ...

This should be reported in the read.me ...
From stackoverflow : (by Eduardo Quintana)

"Use event delegation this will add the handler for future elements.

If you use $(".button") and the element is not in the DOM already the event handler will not work because noting will be selected

$(document).on("click",".button",function(){
console.log('click');
});
"

hope to help,
Raf

expose 'has' function

currently has is not exposed in the $.Mustache public api, it would be handy to use

README load example seems incorrect

Judging from the code, it looks like this example from the README:

var viewData = { name: 'Jonny' };
$.Mustache.load('./templates/greetings.htm')
    .done(function () {
        $('body').mustache('simple-hello', viewData);
    });
});

should instead be

var viewData = { name: 'Jonny' };
$.Mustache.load('./templates/greetings.htm', function () {
        $('body').mustache('simple-hello', viewData);
});

domTemplateType misdocumented

The docs say that in order for addFromDom() to work the scripts must be of type "text/template", but the source hints it's "text/html".

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.