Git Product home page Git Product logo

blueimp / javascript-templates Goto Github PK

View Code? Open in Web Editor NEW
1.7K 111.0 661.0 960 KB

1KB lightweight, fast & powerful JavaScript templating engine with zero dependencies. Compatible with server-side environments like node.js, module loaders like RequireJS and all web browsers.

Home Page: https://blueimp.github.io/JavaScript-Templates/

License: MIT License

JavaScript 67.90% CSS 10.84% HTML 20.50% Shell 0.77%

javascript-templates's Introduction

JavaScript Templates

Contents

Description

1KB lightweight, fast & powerful JavaScript templating engine with zero dependencies.
Compatible with server-side environments like Node.js, module loaders like RequireJS or webpack and all web browsers.

Usage

Client-side

Install the blueimp-tmpl package with NPM:

npm install blueimp-tmpl

Include the (minified) JavaScript Templates script in your HTML markup:

<script src="js/tmpl.min.js"></script>

Add a script section with type "text/x-tmpl", a unique id property and your template definition as content:

<script type="text/x-tmpl" id="tmpl-demo">
  <h3>{%=o.title%}</h3>
  <p>Released under the
  <a href="{%=o.license.url%}">{%=o.license.name%}</a>.</p>
  <h4>Features</h4>
  <ul>
  {% for (var i=0; i<o.features.length; i++) { %}
      <li>{%=o.features[i]%}</li>
  {% } %}
  </ul>
</script>

"o" (the lowercase letter) is a reference to the data parameter of the template function (see the API section on how to modify this identifier).

In your application code, create a JavaScript object to use as data for the template:

var data = {
  title: 'JavaScript Templates',
  license: {
    name: 'MIT license',
    url: 'https://opensource.org/licenses/MIT'
  },
  features: ['lightweight & fast', 'powerful', 'zero dependencies']
}

In a real application, this data could be the result of retrieving a JSON resource.

Render the result by calling the tmpl() method with the id of the template and the data object as arguments:

document.getElementById('result').innerHTML = tmpl('tmpl-demo', data)

Server-side

The following is an example how to use the JavaScript Templates engine on the server-side with Node.js.

Install the blueimp-tmpl package with NPM:

npm install blueimp-tmpl

Add a file template.html with the following content:

<!DOCTYPE HTML>
<title>{%=o.title%}</title>
<h3><a href="{%=o.url%}">{%=o.title%}</a></h3>
<h4>Features</h4>
<ul>
{% for (var i=0; i<o.features.length; i++) { %}
    <li>{%=o.features[i]%}</li>
{% } %}
</ul>

Add a file server.js with the following content:

require('http')
  .createServer(function (req, res) {
    var fs = require('fs'),
      // The tmpl module exports the tmpl() function:
      tmpl = require('./tmpl'),
      // Use the following version if you installed the package with npm:
      // tmpl = require("blueimp-tmpl"),
      // Sample data:
      data = {
        title: 'JavaScript Templates',
        url: 'https://github.com/blueimp/JavaScript-Templates',
        features: ['lightweight & fast', 'powerful', 'zero dependencies']
      }
    // Override the template loading method:
    tmpl.load = function (id) {
      var filename = id + '.html'
      console.log('Loading ' + filename)
      return fs.readFileSync(filename, 'utf8')
    }
    res.writeHead(200, { 'Content-Type': 'text/x-tmpl' })
    // Render the content:
    res.end(tmpl('template', data))
  })
  .listen(8080, 'localhost')
console.log('Server running at http://localhost:8080/')

Run the application with the following command:

node server.js

Requirements

The JavaScript Templates script has zero dependencies.

API

tmpl() function

The tmpl() function is added to the global window object and can be called as global function:

var result = tmpl('tmpl-demo', data)

The tmpl() function can be called with the id of a template, or with a template string:

var result = tmpl('<h3>{%=o.title%}</h3>', data)

If called without second argument, tmpl() returns a reusable template function:

var func = tmpl('<h3>{%=o.title%}</h3>')
document.getElementById('result').innerHTML = func(data)

Templates cache

Templates loaded by id are cached in the map tmpl.cache:

var func = tmpl('tmpl-demo'), // Loads and parses the template
  cached = typeof tmpl.cache['tmpl-demo'] === 'function', // true
  result = tmpl('tmpl-demo', data) // Uses cached template function

tmpl.cache['tmpl-demo'] = null
result = tmpl('tmpl-demo', data) // Loads and parses the template again

Output encoding

The method tmpl.encode is used to escape HTML special characters in the template output:

var output = tmpl.encode('<>&"\'\x00') // Renders "&lt;&gt;&amp;&quot;&#39;"

tmpl.encode makes use of the regular expression tmpl.encReg and the encoding map tmpl.encMap to match and replace special characters, which can be modified to change the behavior of the output encoding.
Strings matched by the regular expression, but not found in the encoding map are removed from the output. This allows for example to automatically trim input values (removing whitespace from the start and end of the string):

tmpl.encReg = /(^\s+)|(\s+$)|[<>&"'\x00]/g
var output = tmpl.encode('    Banana!    ') // Renders "Banana" (without whitespace)

Local helper variables

The local variables available inside the templates are the following:

  • o: The data object given as parameter to the template function (see the next section on how to modify the parameter name).
  • tmpl: A reference to the tmpl function object.
  • _s: The string for the rendered result content.
  • _e: A reference to the tmpl.encode method.
  • print: Helper function to add content to the rendered result string.
  • include: Helper function to include the return value of a different template in the result.

To introduce additional local helper variables, the string tmpl.helper can be extended. The following adds a convenience function for console.log and a streaming function, that streams the template rendering result back to the callback argument (note the comma at the beginning of each variable declaration):

tmpl.helper +=
  ',log=function(){console.log.apply(console, arguments)}' +
  ",st='',stream=function(cb){var l=st.length;st=_s;cb( _s.slice(l));}"

Those new helper functions could be used to stream the template contents to the console output:

<script type="text/x-tmpl" id="tmpl-demo">
  <h3>{%=o.title%}</h3>
  {% stream(log); %}
  <p>Released under the
  <a href="{%=o.license.url%}">{%=o.license.name%}</a>.</p>
  {% stream(log); %}
  <h4>Features</h4>
  <ul>
  {% stream(log); %}
  {% for (var i=0; i<o.features.length; i++) { %}
      <li>{%=o.features[i]%}</li>
      {% stream(log); %}
  {% } %}
  </ul>
  {% stream(log); %}
</script>

Template function argument

The generated template functions accept one argument, which is the data object given to the tmpl(id, data) function. This argument is available inside the template definitions as parameter o (the lowercase letter).

The argument name can be modified by overriding tmpl.arg:

tmpl.arg = 'p'

// Renders "<h3>JavaScript Templates</h3>":
var result = tmpl('<h3>{%=p.title%}</h3>', { title: 'JavaScript Templates' })

Template parsing

The template contents are matched and replaced using the regular expression tmpl.regexp and the replacement function tmpl.func. The replacement function operates based on the parenthesized submatch strings.

To use different tags for the template syntax, override tmpl.regexp with a modified regular expression, by exchanging all occurrences of "{%" and "%}", e.g. with "[%" and "%]":

tmpl.regexp = /([\s'\\])(?!(?:[^[]|\[(?!%))*%\])|(?:\[%(=|#)([\s\S]+?)%\])|(\[%)|(%\])/g

By default, the plugin preserves whitespace (newlines, carriage returns, tabs and spaces). To strip unnecessary whitespace, you can override the tmpl.func function, e.g. with the following code:

var originalFunc = tmpl.func
tmpl.func = function (s, p1, p2, p3, p4, p5, offset, str) {
  if (p1 && /\s/.test(p1)) {
    if (
      !offset ||
      /\s/.test(str.charAt(offset - 1)) ||
      /^\s+$/g.test(str.slice(offset))
    ) {
      return ''
    }
    return ' '
  }
  return originalFunc.apply(tmpl, arguments)
}

Templates syntax

Interpolation

Print variable with HTML special characters escaped:

<h3>{%=o.title%}</h3>

Print variable without escaping:

<h3>{%#o.user_id%}</h3>

Print output of function calls:

<a href="{%=encodeURI(o.url)%}">Website</a>

Use dot notation to print nested properties:

<strong>{%=o.author.name%}</strong>

Evaluation

Use print(str) to add escaped content to the output:

<span>Year: {% var d=new Date(); print(d.getFullYear()); %}</span>

Use print(str, true) to add unescaped content to the output:

<span>{% print("Fast &amp; powerful", true); %}</span>

Use include(str, obj) to include content from a different template:

<div>
  {% include('tmpl-link', {name: "Website", url: "https://example.org"}); %}
</div>

If else condition:

{% if (o.author.url) { %}
<a href="{%=encodeURI(o.author.url)%}">{%=o.author.name%}</a>
{% } else { %}
<em>No author url.</em>
{% } %}

For loop:

<ul>
{% for (var i=0; i<o.features.length; i++) { %}
    <li>{%=o.features[i]%}</li>
{% } %}
</ul>

Compiled templates

The JavaScript Templates project comes with a compilation script, that allows you to compile your templates into JavaScript code and combine them with a minimal Templates runtime into one combined JavaScript file.

The compilation script is built for Node.js.
To use it, first install the JavaScript Templates project via NPM:

npm install blueimp-tmpl

This will put the executable tmpl.js into the folder node_modules/.bin. It will also make it available on your PATH if you install the package globally (by adding the -g flag to the install command).

The tmpl.js executable accepts the paths to one or multiple template files as command line arguments and prints the generated JavaScript code to the console output. The following command line shows you how to store the generated code in a new JavaScript file that can be included in your project:

tmpl.js index.html > tmpl.js

The files given as command line arguments to tmpl.js can either be pure template files or HTML documents with embedded template script sections. For the pure template files, the file names (without extension) serve as template ids.
The generated file can be included in your project as a replacement for the original tmpl.js runtime. It provides you with the same API and provides a tmpl(id, data) function that accepts the id of one of your templates as first and a data object as optional second parameter.

Tests

The JavaScript Templates project comes with Unit Tests.
There are two different ways to run the tests:

  • Open test/index.html in your browser or
  • run npm test in the Terminal in the root path of the repository package.

The first one tests the browser integration, the second one the Node.js integration.

License

The JavaScript Templates script is released under the MIT license.

javascript-templates's People

Contributors

blueimp avatar steelywing 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  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

javascript-templates's Issues

problems with jquery 1.9

There is a smaller problem with jquery 1.9 in that the new jquery does not allow whitespace to be "first" in the html string, ie $("

test

") is allowed but $("

test

") is not allowed.

this makes it harder to have "pretty" templates in your code when using it with jquery.
for example

<script id="test">

test

</script>

will fail when used with
$(tmpl("test"))

since the template result will start with "whitespace" characrters (return, space, etc)

at the moment the workaround for me is to use the $.parseHTML function so that I now get

$($.parseHTML(tmpl("test")))

Is there any way to make it "trim" the whitespace at the beginning (and at the end) automaticly?

Uncaught TypeError: Cannot read property 'innerHTML' of null

This might be an error of some element I'm missing (I'm munging the jQuery uploader demo page into my existing upload page that used plupload)... but I can't tell because the tmpl.min.js (which Chrome inspector is throwing the error on) is minified.

Return empty string instead of "undefined" on non-existent variables

On line 69 (first line of tmpl.encode) I added this super simple patch to return an empty string instead of the string "undefined" when a specific value is not passed to the function.

if (!s) return '';

Figured I'd at least put it out here in case others are looking for the same thing, and maybe it's something you want to include (or know a more correct way for).

Thanks for a super simple-to-use, slim and awesome lib.

Using template on multiple classes

Hi @blueimp,

I'm using your Jquery file upload on with the basic ui plus version on my website, which includes javascript-templates.

I'm trying to get another script the same as the <script id="template-download" type="text/x-tmpl">...</script> but with being sent to a different class and slight changes within the script.

I just wondering what would be the easiest way to accomplish this between the editing the scripts in the index.html and the jquery.fileupload-ui.js?

JavaScript-Templates doesn't output 0 (zero)

I really don't know whether it's my fault, but I just can't make this library output a 0.

Here's the template

{% for (var i=0; i<o.numbers.length; i++) { %}
    <li>{%=o.numbers[i]%}</li>
{% } %}
</ul>

Here's the JavaScript object

{
    "numbers": [0, 1, 2, 3, 0, 1, 2, 3, 0]
}

All the other numbers are in the output except for number 0.

Tested in Chrome, Firefox and IE. Same issue was found.

thank you

hi blueimp,

i didn't know how else to thank you for making this template plugin so thought i'd just leave the message here. I've always been looking for a simple templating mechanism for JSON data (awesome for $.ajax, success:function(data)!) and this is a huge help!!!

one question, can you tell me what are other ways people render JSON data as HTML? Your templating engine is still quite new and I'm wondering what are common/popular ways people have been dealing with JSON until now.

any thoughts would be greatly appreciated,

thanks,
tim

jQuery Events

Hello,

I'm working on a project that uses the upload script with the template script (tmpl).

However, when the tmpl() creates an element based on a template within a <script></ script>, the element receives no event previously assigned of jQuery.
I know this is natural, but I wonder if there is anything that can be done.

I thought of a solution:

  • If the template can be passed in the form of element jQuery $(elem), this may have come with the assigned events. I know the tmpl() runs without jQuery, but a validation could help.

How to access global function in template?

I read "Local helper variables" and test the code by print().

But it does not working with global object function...

sample code

Have any idea?

btw:
I know I can change raw data before using template, but i just want know can template do it?

Not very popular

This is not a code issue per se, but I think it is a issue to be discussed. Why tmpl is not very popular? I'm using for a few months, after switching from jsrender and I'm loving it. But when I google for the fastest or the best engine nobody mention it. Like this template chooser for exemple: http://garann.github.com/template-chooser/

I think I only knew about tmpl after searching here at Github. I maybe complaining about nothing but I guess popular code evolves fast, because there is more people around it.

To make sure how good is tmpl I edited a jsPref test, take a look: http://jsperf.com/hogan-vs-dot-js-vs-trimpath-zepto-js/7

So keep up the good work and let me know if there's something I can do to help.

Compiled template problem

According to documentation, compiled my templates to external file:
tmpl.js templates/test/test.html > tmpl-templates.min.js

Documentation wrote: The generated file can be included in your project as a replacement for the original tmpl.js runtime. But this is not true - if I include only tmpl-templates.min.js, in same html page write new template with <script type="text/x-tmpl" id="new1">test</script>, I can't use tmpl("new1"), only templates, described in test.html. What I'm doing wrong? Including plain tmpl.min.js with tmpl-templates.min.js does not help. I think, compiled version must fill the templates cache and leave other template behavior unchanged.

TypeError: o.files is undefined

hello,,
i have this error in the console.. What i am trying to do is that get the uploaded files from the database and i want to give them to the template engine to build up the download template. Here is the code:

$('.files').html(tmpl("template-download",jsn));

here is a sample of my json string:

[
{
name:"asasdjhgdsjgasdh.jpg",
thumbnail_url:"http://localhost/.....jpg",
url:"http://localhost/........pg",
type:"jpg",
size:"270 mb",
delete_url:"http://localhost/...../UploadHandler.ashx"
},
..
..
..
etc
]

thanks in advance :)

Templates as an external file when using them in client-side

I read the documentation on the project home page and tried to implement it on a project of mine and it worked as expected.

Although having the template inside a script tag inline in the HTML is something I would like to avoid.

I tried moving the template to an external file and reference it with the src attribute but it didn't work.

<script type="text/x-tmpl" id="template" src="template.js"></script>

I even forced the headers sent by template.js but no luck either.

Why is it that reference it as an external file doesn't work? Is there a way to have the template external to the HTML code?

Right now I by-pass this issue including them with PHP, but most of all I would like to know why it fails as an external file in the script tag.

0 (number) is not rendered

Example:

var template = tmpl('#template', {n: 0});
$(body).append(template);

<body>
<script id="template" type="text/x-templ">
<p>N = {%=o.n%}</p>
</script>
</body>

Result will be:
<p>N = </p>

But when the data is {n: '0'} that's OK
<p>N = 0</p>

upload outside the project root

Good night! I implemented this upload folder with dynamics and I'm having trouble following line:
$ ('# fileupload'). fileupload ({
url: '.. / training / views / person / index.php? folder = ',
maxFileSize: 100000000,
acceptFileTypes: / (. | \ /) (JPE? g) $ / i
});
This url I have to go back to him because he shares a folder with another project that was uploaded.
Can someone help me!

add with(o) statement for avoid o. object referrence

this is my source code
...
var tmpl = function (str, data) {
var f = !/[^\w-.:]/.test(str) ? tmpl.cache[str] = tmpl.cache[str] ||
tmpl(tmpl.load(str)) :
new Function(
tmpl.arg + ',tmpl',
"var _e=tmpl.encode" + tmpl.helper + ";with("+tmpl.arg+") {_s='" +
str.replace(tmpl.regexp, tmpl.func) +
"';return _s;}"
);
//alert(f)
return data ? f(data, tmpl) : function (data) {
return f(data, tmpl);
};
};
...

add with("tmpl.arg") for avoid o. object referrence.

{%= o.title %} ===> {%= title %}

Array: can't loop through loop

I have JSON structure:

{
"prices":[
{
"name": "Market 1",
"rows":[
{
"name": "test1",
"price": "4,25",
"rate": "+0,05"
},
{
"name": "test2",
"price": "4,12",
"rate": "+0,02"
}
]
},
{
"name": "Market 2",
"rows":[
{
"name": "test1",
"price": "4,25",
"rate": "+0,05"
},
{
"name": "test2",
"price": "4,12",
"rate": "+0,02"
}
]
}
]}

In my template i want to control all objects like:

{% for (var i=0; i<o.prices.length; i++) { %}
{%=o.prices[i].name%}

{% for (var j=0; j<o.prices[i].rows.lenght; j++) { %}
       show me something
   <span class="tb-txt">{%=o.prices[i].rows[j].name%}</span>
{% } %}

{% } %}

The first loop works, i see the name of each object.. but the 2nd loop doesnt work, i get no errors in the console, but it's now showing up. 'Show me something' isn't visible either.

Is this a bug?

Is it able to use effects of jquery ? (FadeIn, FadeOut)

hi blueimp,
Really appreciate your wokrs. Just using your jQuery-Fiile-Uploader.
Faced a problem while changing the template.Tried to use FadeIn and FadeOut when returning Error, but coudn't get it.
Is it able to use jquery effect in template ? Example:
{% if (file.error) { %}
$(".error").fadeIn(2000);

Error {%=file.error%}
.

Thanks.

How to use Mod (%) operator in blueimp javascript template

I wanted to use an expression that contains Mod (%) operator but the template generates an error saying : "SyntaxError: illegal character". How can I get rid of it.

My code is something like below:

{%
for( var i = 0, venue; venue = o[i] ; i++){

if( ! (i % 2) ) {
// do something with 'venue'
}

}
%}

CDATA

<script id="foobar" type="text/html">
  //<![CDATA[
    code / template
  //]]>
</script>

if you use it without CDATA it will not validate as xhtml.
I my self use html5 where it doesn't matter, but some people do care about that, and so does the framework I want to use it with.
Is there a chance this script will support the use of templates with // in it?
(So far the template output is messed up, it doesn't output anything between start and the first variable in the template)

IE7 & IE8 Invalid procedure call or argument

I hate to bring this kind of "bugs", but I get this "invalid procedure call or argument" when using IE7 and IE8 and it stops all further javascript execution, right here:
tmpl.js, line 35 character 9

tmpl.load = function (id) {
        return document.getElementById(id).innerHTML; <--
};

Using

  • tmpl.js v 2.1.0
  • jquery 1.8.2
  • jquery-ui 1.9.0
  • jquery.fileupload 5.19.3

rendering html

this has to be a really simple problem, but am just not able to figure out why I can't render the "comment" html to make it bold.

here's the code:

$('button').on('click, function(){
var data={  "review_id": 7, "comment" : "<span style="font-weight:bold">hello</span>"};
    document.getElementById("commentList").innerHTML = tmpl("tmpl-comment", data);
});
</script>
<button>tmpl</button>
<ul id="commentList"></ul>
<script type="text/x-tmpl" id="tmpl-comment">

    <li id="{%=o.review_id%}">{%=o.comment%}</li>
</script>

any thoughts?

thanks,
tim

Trying to replace a variable with object.

Hi,
When i try to replace a variable in template with object value.
it returns [object Object].

template:
"license": {%=map.license%};

data:
{
"title": "JavaScript Templates",
"license": {
"name": "MIT license",
"url": "http://www.opensource.org/licenses/MIT"
},
"features": [
"lightweight & fast",
"powerful",
"zero dependencies"
]
}

output:
"license" : [object Object].

Any way to get
"license": {
"name": "MIT license",
"url": "http://www.opensource.org/licenses/MIT"
}

Calling another template with include

I realize it's possible to use the include() helper function to reference another template from within a template, but is it possible to pass the included template part of the JSON object used on the original template?

Example: I've got a template that loops through an array of JSON objects with a for loop.

<script id="tmpl-interviews" type="text/x-tmpl">
    {% for (var i = 0; i < o.brief.shot.length; i++) { %}
    ...
    {% include('tmpl-interviewees", o.brief.shot[i]); %}
    ...
    {% } %}
</script>

The included template would loop through a nested array of JSON objects representing interviewees.

<script id="tmpl-interviewees" type="text/x-tmpl">
    {% for (var j = 0, innerCount = j+1; j < o.meta.length; j++, innerCount++) { %}
    // output interviewees
    {% } %}
</script>

Is this even possible in a format like this? I've made the assumption that it's legit to pass the object being used in the root template through to the included template, but it doesn't work for me.

datepicker in this?

how do you execute script against a control created using this?
so if i have a text box that is bound to say {%=o.license.name%} how would i add a script to extend that?
What i am trying to do is turn one of the fields loaded using this method into a datepicker and the datepicker requires javascript to initialise

Thanks in advance!

Using templates inside javascript

Hey,

I was wondering how you would go about using the templates inside javascript ? That is - when you don't have access to the

<script type="text/x-tmpl" id="tmpl-demo">

Basically, the templates rock - but I want to use them within a javascript file ? Is that possible ?

jQuery 1.9.0 support?

This doesn't seem to work with jQuery 1.9.0

I get errors like this:

Uncaught Error: Syntax error, unrecognized expression: <li class="upload-item" data-datas-index="">
  <a class="close" href="#"><i class="icon-remove"></i></a>
  <p class="file-type bold">mov</p>
  <p class="file-name arial">2011-12-15 21.36.43.mov</p> 
  <p class="file-name arial">4.48 MB</p>
  <div class="progress"><div class="bar progress-bar" style="width: 0%"></div></div>
</li> 

When I switch back to jQuery 1.8.3 it works fine.

using custom functions within JavaScript Templates

In my template I'd like to format my dates and have them update periodically.

I saw the following in the documentation:

<span>Year: {% var d=new Date(); print(d.getFullYear()); %}</span>

my question is how to use my own custom function, nicetime(), in my template instead of getFullYear().

here's what i'd like to work, but doesn't:

<span>Year: {% var d=nicetime(); print(d); %}</span>

here's what nicetime() looks like:

function nicetime(){ var time = new Date(), comment_date = setInterval(function() { var time2 = time_since(time.getTime()/1000); return time2; // 1 second ago, then 2 seconds ago, and so on... }, 1000); }

time_since() formats the code in Facebook-style: "2 seconds ago...".

any thoughts would be greatly appreciated?

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.