GithubHelp home page GithubHelp logo

nolimits4web / template7 Goto Github PK

View Code? Open in Web Editor NEW
653.0 41.0 166.0 426 KB

Mobile-first JavaScript template engine

Home Page: http://www.idangero.us/template7/

License: MIT License

JavaScript 100.00%

template7's Introduction

template7's People

Contributors

ichuan avatar jasonkleban avatar lalakla avatar nolimits4web avatar pi0 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

template7's Issues

Предложение: реализовать возможность в js_if подниматься на уровень "вверх", как в обычном if

{{../person}} - так мы поднимемся вверх при выводе
{{#if ../person}} - так мы сделаем проверку на уровне выше

А вот для js_if - нельзя подняться вверх. this - это текущий уровень. Было бы здорово что-то типа такого:
{{#js_if "this.parent.person=='123'"}}

how to equal two variables from different contexts?

My template context object example:

{
    label: "Image Size",
    current: "3872x2592",
    choices: [
        "3872x2592",
        "2896x1944",
        "1936x1296"
    ]
}

my template:

{{#if choices}}
  <select name="{{label}}">
    {{#each choices}}
    <option value="{{@index}}" {{#js_compare "this == current"}}selected{{/js_compare}} >
      {{this}}
    </option>
    {{/each}}
  </select>
{{/if}}

I need compare every item in {{#each}} block with variable from parent context (in my case variable current)
I tried:

  • current
  • {{../current}}
  • ../current

... no success.
Is it possible?
Thanks for answer :)

two questions

  • It is possible only to set the path of the template and another object to compile in a div?
  • It is necessary to always declare<script>to view all?

EvalError of 'js' and ‘js_compare’

I got an EvalError at

eval.call(this, func).call(this)

on an old ipad

version: ios 6.1.3
error description: this value passed to eval must be the global object from which eval originated

Performance?

From the template7 site:

It is ultra lightweight (around 1KB minified and gzipped) and blazing fast (up to 2-3 times faster than Handlebars in mobile Safari).

Do you have anything to back up those performance claims, just genuinely curious. Thanks!

How to access sub objects in a loop

Hi

How can I loop through the following object properly.

Here is my JSON before I parse it with JSON.parse();

[{
  "id": "1",
  "title": "Article Title 1",
  "videos": [
        {"title":"Video Title 1"},
        {"title":"Video Title 2"},
        {"title":"Video Title 3"}
   ]
},
{
  "id": "2",
  "title": "Article Title 2",
  "videos": [
        {"title":"Video Title 1"},
        {"title":"Video Title 2"},
        {"title":"Video Title 3"}
   ]
}]

I have tried the following but it spits out loads of video titles. It is not looping properly and I can't figure out how to access to sub object loop right. Is it even possible?

{{#each articles}}
    <h2>{{this.title}}</h2>
    {{#each this.videos}}
         <h3>{{this.videos.title}}</h3>
    {{/each}}
{{/each}}

It kind of just ends up spitting out every singe sub video in one.

Would really appreciate anyone's help on this.

Cheers

Access @key of parent loop in nested each loops

Tried the following:

{{#each array1}}
{{#each array2}}
  {{../@key}} // how to access array1 key here?
{{/each}}
{{/each}}
{{#each array1}}
{{#each array2}}
  {{@../key}} // how to access array1 key here?
{{/each}}
{{/each}}

but none worked.
Any ideas?
Thanks.

Getting started, "Template7" undefined

I'm trying a first "getting started" page with Template7 but I'm stuck...

What is wrong with the following code ? I get "'Template7' is undefined" error.

All referred js files are accessible, I get no 404 errors, only 200.

<html>
<head>
<script src="template7.min.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$(function() {
	var template = $("#template").html();
	var compiledTemplate = Template7.compile(template);  // Error here
	jQuery.getJSON("http://api.fixer.io/latest", null, function(data) {
		$("#result").html(compiledTemplate(data));
	});
});
</script>
</head>
<body>

<div id="result"></div>

<script id="template" type="text/template7">
    <p>Base currency: {{base}}</p>
</script>

</body>

Variables starting with "this"

We are experiencing issues with this particular block of code in src/template7.js (line 240):

if (part.indexOf('this') === 0) {
    variable = part.replace('this', ctx);
}

If I am using a variable with the word "this" at the beginning (i.e. "this_variable" or "thisVariable") the template breaks. I changed the above block to the following and haven't had an issue:

if (part == 'this') {
    variable = part.replace('this', ctx);
}

I'm not sure this is the correct solution, I just wanted to let you all know of the issue.

the doc partof #js_compare is wrong, it lost context

in doc #js_compare be used like :

{{#js_compare "a === b"}}A equals to B{{else}}A not equal to B{{/js_compare}}

i use #js_compare in a {{#each}} like
"{{#js_compare "sales == 1"}}1{{else}}2{{/js_compare}}"
but i get error "sales not defined"

the sales lost it context . in right way like
"{{#js_compare "this.sales == 1"}}1{{else}}2{{/js_compare}}"

unsafe-eval

image

popover

<script id="template" type="text/template7">
    <p>Hello, my name is {{firstName}} {{lastName}}</p>
</script>

script

var context = {
            firstName: 'John',
            lastName: 'Doe'
        };

        $$.get("view/popover.html", {}, function(template) {
            console.log(template);
            var compiledTemplate = Template7.compile(template);
            var html             = compiledTemplate(context);
            $$('.teste').html(html);
        });

It should not work?

Escaping bug

1st problem

1.

Params
{
    text: '<script>alert(1)<\/script>'
}
Template
{{text}}
Output

Empty string

2.

Params

{
    text: '<foo>alert(1)<\/foo>'
}
Template
{{text}}
Output
alert(1)

3.

Params

{
    text: '&lt;foo&gt;alert(1)&lt;/foo&gt;'
}
Template
{{text}}
Output
<foo>alert(1)</foo>

Expected

Output
<foo>alert(1)</foo>

For all use-cases!

2nd problem

Params

{
    text: '&lt;foo&gt;alert(1)&lt;/foo&gt;'
}
Template
{{{text}}}
Output

Error

Expected

&lt;foo&gt;alert(1)&lt;/foo&gt;

Should work like Handlebars

Template7: Template must be a string

var template = $$('script#template').html();

console.log(template)

var compiledTemplate = Template7.compile(template);
<script id="template" type="text/template7">
          <ul>
            {{#each droplets}}
              <li>{{id}} {{name}}</li>
            {{/each}}
          </ul>
        </script>

it doesn't work framework7

Using parent access in with + if doesn't work correctly

I can't really explain what's wrong, but an example will probably say enough. Here's a complete fiddle: https://jsfiddle.net/Toverbal/7gc9br80/

Data:

var data = {
  level1: {
     level2: 'This is level 2!',
  },
  withwrapper: {
    content: 'This is dummy content',
  },
};

Template (this is just a snippet from the complete fiddle!):

  {{#with withwrapper}}
    {{#if ../level1}}
      <div>This fails: {{ ../level1.level2 }}</div> 
    {{/if}}
  {{/with}}

Strange thing is that ../../level1.level2 will give result and if you don't add the #if, the ../level1.level2 actually works.

Unable to retrieve @root context in partial template

The registered partial template can't access the @root context:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Template7 bug</title>
</head>
    <body>
        <div id="template"></div>
        <script src="../dist/template7.min.js"></script>
        <script>
            T7bug = {
                context: {
                    rootvalue: 'this is missing',
                    items: [
                        {
                            content: 'one'
                        },
                        {
                            content: 'two'
                        },
                        {
                            content: 'three'
                        }
                    ]
                },
                template: [
                    '<ul>',
                    '   {{#each items}}',
                    '       {{> partial}}',
                    '   {{/each}}',
                    '</ul>'
                ].join(''),
                partial: [
                    '<li>',
                    '    <div>rootvalue: {{@root.rootvalue}}',
                    '       <div>{{content}}</div>',
                    '    </div>',
                    '</li>'
                ].join('')
            };

            Template7.registerPartial('partial', T7bug.partial);
            var template = Template7.compile(T7bug.template);
            var html = template(T7bug.context);
            document.getElementById('template').innerHTML = html;

        </script>
    </body>
</html>

In the example above the @root.rootvalue is not rendered.

Problem with js_if and special "@" variables

For example below code returns always true (even when selectedMenuID is different than ID):
{{#js_if "@root.selectedMenuID===this.ID"}}

but this version seems works correct (contains space before ===):
{{#js_if "@root.selectedMenuID ===this.ID"}}

this is inconsistent in comparison to other js_if expression, for example this works correct without space:
{{#js_if "123456===this.ID"}}

partial helper: use variable as partial name

Hi,

It would be nice to be able render a partial using a variable as helpernmae.
Currently helper doesn't make difference between "partialname" or partialname (without double quotes).

What I mean is considering following partials names:

  1. text
  2. textarea
  3. select
    ...

And a variable called type that can contains "text", "textarea" or "select"
I would like to be able to achieve the following
{{> type}}

And so partial helper should resolve properly name.
Regards

Template7 Do not support table structure

{{#each datalist}}
 <tr>
       <td>{{Number}}</td>
</tr>
{{/each}}

views error
---------------------------------Magic split line---------------------------------
{{#each datalist}}
 <ul>
       <li>{{Number}}</li>
</ul>
{{/each}}

views ok

Templating - respect spaces

i got an error when compiling e.g.
´´´
{{ emails.all }}
´´´
note the spaces!
by deleting the spaces {{emails.all}} i got the correct template/output/no error.
I could live with that but i think the parsing should be more graceful in this case.

why block.contextName.length lt 0

if (block.contextName.length > 0) {
throw new Error('Template7: Missing helper: "' + block.helperName + '"');
}
if request contextName length lt 0 while this param is unless

Demo broken

Links to the images in your demo are broken. Server not found error.

Example for #js_compare is wrong

All of the variables in the example should be prefixed with 'this.', even says so in the caption below.

Also the caption contains a typo. It says 'Nore' instad of 'Note'

Minor stuff really.

unless with a test as context

Hello,

Can I use a test function as context for #unless helper. I have read in source that a test on context is made at the top of the function but I can make it work.

{{#unless function(){ return var === "test";} }}
    ...
{{/unless}}

maybe it could be easier to do something like that :

{{#unless (var === test) }}
    ...
{{/unless}}

Regards

Bug - Unable to retrieve parent context in each helper

I could't get variable in parent context by passing ../Variable when using in block expressions. This feature was working till v1.1.4 release. After upgrading to v.1.2.3 it is not working.

Template7

{{#each children}}
    {{#each grandChildren}} 
        grandFatherName: {{../../firstName}} | fatherName: {{../name}} |  name:{{name}}<br/>
    {{/each}} 
{{/each}}")

Data

{
   firstName: 'Ivan',
   children:[
         {
          name: 'Vasiliy',
          age: 35,
          grandChildren:[
                         {name: 'Olga', age: 10},
                         {name: 'Masha', age: 6}
                        ]
         }
   ]
}

Expected:

grandFatherName: Ivan | fatherName: Vasiliy |  name: Olga
grandFatherName: Ivan | fatherName: Vasiliy |  name: Masha

Output:

grandFatherName:  | fatherName:  |  name: Olga
grandFatherName:  | fatherName:  |  name: Masha

There are no parents variables value.

For loop expression

support "for" loop expression in the form of native javascript inside the template.
Basically I need (having provided an item COUNT) to generate repetitive tamplate chunk.

enhance Template7.registerPartial

Would be nice to enhance this method:

  • Template7.registerPartial(name, template)

with templateURL

Template7.registerPartial(name, templateURL)

where templateURL is a template.html file, which includes the template.

It is not good maintainable to have html-strings in javascript..

Root Compare

how to set this condition with {{#js_compare "@root.title == about"}}

Access @key inside a custom helper

Hello @nolimits4web,

How can I access the "@key" inside of the "inArray" helper?

{{#each manyItems}}        
    {{#inArray 'something' this.itemName}}
        {{../@key}} <!-- This works -->
        {{../@index}} <!-- This works, too -->
        {{@root.someItems[../@key].id}} <!-- This doesn't work. How to access the ../@key here? -->
    {{/inArray}}
{{/each}}

Hope you can help me ;)

Ability to get item by index

Great work on Template7, can you add the ability to get item by index e.g:
{{clients.1.name}} or {{clients.[1].name}}
It would be cool if you could. Thanks.

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper App’s white list on Github. You'll find this list on your repo or organization’s settings page, under Installed GitHub Apps.

publish to bower

Will you publish Template7 standalone library in bower ?

I am waiting for it in Framework7 0.9.6 but now I have to use this repository manually.

Format variables

Hey,
is it possible to format variables before they get rendered? I want to convert "pubDate" in RSS Feeds into DAY. MONTH YEAR (e.g. 16. January 2015) scheme?

compile error

Trying to compile with a property that has a space in the name like this:

Template7.compile('{{text test}}')({'text test':'hello'});

But that produces: Error: Template7: Missing helper: "text"

What syntax can correctly compile this?

Tests

Hi,

Are you at all interested in tests for Template7 or do you think it is not useful to have them?

Im asking because i chose T7 as my learning project for testing in mocha+chai+karma, would you like me to create PR after i finish? Im not saying it will be perfect, but certainly it would be better than nothing.

Regards,
Paweł

unsafe-eval is not allowed with CSP

I am using Framework7 together with the baked in Template7. In my html, I have included the meta tag to include Content-Security-Policy.

Expected Behavior
Should work with CSP?

Actual Behavior
'Uncaught EvalError: Refused to evaluate a string as Javascript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "default-src 'self'"
at eval()
at o (framework7.js:13994)

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.