Giter Site home page Giter Site logo

bem / bem-xjst Goto Github PK

View Code? Open in Web Editor NEW
115.0 15.0 48.0 2.43 MB

bem-xjst (eXtensible JavaScript Templates): declarative template engine for the browser and server

Home Page: https://bem.github.io/bem-xjst

License: Other

JavaScript 99.82% Shell 0.03% Python 0.15%
javascript template-engine declarative html-builder bem pattern-matching view

bem-xjst's Introduction

bem-xjst

Declarative template engine for the browser and server with regular JS syntax.

NPM version Build Status Dependency Status devDependency Status Coverage Status

Features

Templates are extensible: they can be redefined or extended

You can redefine or extend just a particular part of output not only by simple redefinition via new templates but also using ‘modes’. E.g. it may be a tag name or its content.

block('link')({ tag: 'span' });
// The template sets tag to `span` for all `link` blocks.
// And tag mode can be redefined if any condition passed.

block('link').match((node, ctx) => ctx.url)({ tag: 'a' });
// The template sets tag to `a` only if block `link` have `url` field.
// Otherwise tag will be ‘span’ as previous template says.

Pattern matching

Templates are written using pattern matching for the values and structure of input data

block('list')({ tag: 'ul' });
block('item')({ tag: 'li' });

We can apply these two declarative-style templates templates to data:

{
  block: 'list',
  content: [
    {
      block: 'item',
      content: {
          block: 'list',
          content: [
              { block: 'item', content: 'CSS' },
              { block: 'item', content: 'HTML' }
          ]
      }
    },
    {
      block: 'item',
      content: {
          block: 'list',
          content: { block: 'item', content: 'JS' }
      }
    }
  ] 
}

The result is:

<ul class="list">
    <li class="item">
        <ul class="list">
            <li class="item">CSS</li>
            <li class="item">HTML</li>
        </ul>
    </li>
    <li class="item">
        <ul class="list">
            <li class="item">JS</li>
        </ul>
    </li>
</ul>

As you can see templates are as simple as CSS.

Automatic recursive traversing upon input data

In the example above you may have noticed that bem-xjst automaticaly traverses input data by content fields. This behaviour is default feature of bem-xjst.

Default rendering

Built-in rendering behavior is used by default, even if the user didn’t add templates. Even without templates. For example from above it will be:

<div class="list">
    <div class="item">
        <div class="list">
            <div class="item">CSS</div>
            <div class="item">HTML</div>
        </div>
    </div>
    <div class="item">
        <div class="list">
            <div class="item">JS</div>
        </div>
    </div>
</div>

That is more than half of the work ;) You will add the salt (couple of templates for tags) and the HTML-soup is very tasty!

No DSL, only JavaScript

Written in JavaScript, so the entire JavaScript infrastructure is available for checking code quality and conforming to best practices.

Since templates is a regular JavaScript code you can use automatic syntax validator from your editor and tools like JSHint/ESLint.

Runs on a server and client

You can use bem-xjst in any browser as well as in any JavaScript VM. We support Node.JS v0.10 and higher.

Tell me more

See documentation:

  1. About
  2. Quick Start
  3. API: usage, methods, signatures and etc
  4. Input data format: BEMJSON
  5. Templates syntax
  6. Templates context
  7. Runtime: processes for selecting and applying templates

Try it

Online sandbox

Online demo allows you to share code snippets, change versions and etc. Happy templating!

Install npm package

To compile bem-xjst, you need Node.js v0.10 or later, and npm.

npm install bem-xjst

Copy-paste example from quick start or see simple example from repository. Then read documentation and start experimenting with bem-xjst.

Is bem-xjst used in production?

Yes. A lot of projects in Yandex and Alfa-Bank, also in opensource projects based on bem-core and bem-components.

Benchmarks

See readme.

Runtime linter

See readme.

Static linter and migration tool for templates

See readme.

Links

bem-xjst's People

Contributors

akvy avatar apsavin avatar arikon avatar basilred avatar baymer avatar dab avatar doctordee avatar dustyo-o avatar fual avatar godfreyd avatar greenkeeperio-bot avatar gulalex181 avatar guria avatar incrop avatar indutny avatar miripiruni avatar mishanga avatar qfox avatar rusposevkin avatar sbmaxx avatar tadatuta avatar veged avatar vithar avatar vkz avatar yeti-or avatar zhdanov 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

bem-xjst's Issues

Push html to `this._str`

Right now it is taken from the return values, but should be probably in this._str for compatibility reasons.

cc @veged: how necessary is this?

AssertionError: "MemberExpression" == "ObjectExpression"

Using bem-xjst @ 0.6.0

The same template (bellow) compiles fine in dev mode, but fails when compiling with optimize: true.

Template:

oninit(function() {
    function JsdtmdContext(ctx) {
        this._ctx = ctx;
        this._start = false;
    }

    var oldApply = exports.apply;
    exports.apply = function(ctx) {
        var ctx_ = new JsdtmdContext(ctx);
        return oldApply(ctx_);
    };
});

match()(function() {
    return 'Boom!';
});

match(this._start === false)(function() {
    this._start = true;
    return apply(this._ctx);
});

Generator:

require('bem-xjst').generate(body, { optimize : fasle });  // compiles fine

require('bem-xjst').generate(body, { optimize : true });  // fails

The full stacktrace:

AssertionError: "MemberExpression" == "ObjectExpression"
    at Body.<anonymous> (/Users/varankinv/src/jsdtmd/node_modules/bem-xjst/node_modules/xjst/lib/xjst/compiler/entities/body.js:253:12)
    at Array.forEach (native)
    at Body.rollOutLocal (/Users/varankinv/src/jsdtmd/node_modules/bem-xjst/node_modules/xjst/lib/xjst/compiler/entities/body.js:250:11)
    at Body.rollOutApply (/Users/varankinv/src/jsdtmd/node_modules/bem-xjst/node_modules/xjst/lib/xjst/compiler/entities/body.js:181:17)
    at Body.rollOutSpecific (/Users/varankinv/src/jsdtmd/node_modules/bem-xjst/node_modules/xjst/lib/xjst/compiler/entities/body.js:146:19)
    at Controller.__execute (/Users/varankinv/src/jsdtmd/node_modules/bem-xjst/node_modules/xjst/node_modules/estraverse/estraverse.js:313:31)
    at Controller.replace (/Users/varankinv/src/jsdtmd/node_modules/bem-xjst/node_modules/xjst/node_modules/estraverse/estraverse.js:488:27)
    at Object.replace (/Users/varankinv/src/jsdtmd/node_modules/bem-xjst/node_modules/xjst/node_modules/estraverse/estraverse.js:556:27)
    at Body.rollOut (/Users/varankinv/src/jsdtmd/node_modules/bem-xjst/node_modules/xjst/lib/xjst/compiler/entities/body.js:117:16)
    at Template.rollOut (/Users/varankinv/src/jsdtmd/node_modules/bem-xjst/node_modules/xjst/lib/xjst/compiler/entities/template.js:55:8)

Compiled template fails on require

In 2.x branch require('./desktop.bundles/index/index.bemhtml.js'); results in

ReferenceError: BEMHTML is not defined
    at __bem_xjst (/Users/tadatuta/Sites/rimarcom-base-xjst2/desktop.bundles/index/index.bemhtml.js:1339:15)
    at /Users/tadatuta/Sites/rimarcom-base-xjst2/desktop.bundles/index/index.bemhtml.js:1355:26
    at Object.<anonymous> (/Users/tadatuta/Sites/rimarcom-base-xjst2/desktop.bundles/index/index.bemhtml.js:1365:3)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at repl:1:1

but vm.runInContext() works.

Reference Docs

Please provide a reference documentation on how to write templates, what is the difference between bem-xjst and xjst and so on.

Fix for elem predicate autoinsertion

The idea about some fix for problem with dev runtime and autoinsertion of elem subpredicate. We can add .elemMatch for using instead of .match in cases when we need custom predicate about elem. So this will allow as for determine difference between custom predicates about elems and other in dev runtime.

Recursion without `!this.elem` autopredicate

Test template:

block('b-bla')(
  def()(function() {
    applyCtx({ block: 'b-bla', elem: 'e' })
  })
)

Test data:

{ "block": "b-bla" }

Test expect result:

<div class="b-bla__e"></div>

replace() works wrong when grouped by predicate

Branch 2.x

block('b1').replace()(function () {
    return { block: 'b2' };
});

works fine (result is a string <div class="b2"></div>) but

block('b1')(replace()(function () {
    return { block: 'b2' };
}));

doesn't apply templates on new context (result is an object { block: 'b2' }).

Verbose output for compilation errors

I have a bemhtml file with following content:

block('')

When I build my project in the production mode I get an error:

AssertionError: "Identifier" == "CallExpression"
    at dive (/home/jifeon/projects/bnsf-adwiki/libs/bem-core/node_modules/bem-xjst/lib/bemhtml/compiler.js:317:12)
    at Compiler.flatten (/home/jifeon/projects/bnsf-adwiki/libs/bem-core/node_modules/bem-xjst/lib/bemhtml/compiler.js:355:10)
    at Compiler.pretranslate (/home/jifeon/projects/bnsf-adwiki/libs/bem-core/node_modules/bem-xjst/lib/bemhtml/compiler.js:91:22)
    at Compiler.translate (/home/jifeon/projects/bnsf-adwiki/libs/bem-core/node_modules/bem-xjst/lib/bemhtml/compiler.js:105:14)
    at Compiler.generate (/home/jifeon/projects/bnsf-adwiki/libs/bem-core/node_modules/bem-xjst/lib/bemhtml/compiler.js:692:14)
    at Object.generate (/home/jifeon/projects/bnsf-adwiki/libs/bem-core/node_modules/bem-xjst/lib/bemhtml/api.js:16:40)
    at exports.techMixin.getCompiledResult (/home/jifeon/projects/bnsf-adwiki/libs/bem-core/.bem/techs/bemhtml.js:46:24)
    at _fulfilled (/home/jifeon/projects/bnsf-adwiki/node_modules/bem/node_modules/q/q.js:798:54)
    at self.promiseDispatch.done (/home/jifeon/projects/bnsf-adwiki/node_modules/bem/node_modules/q/q.js:827:30)
    at Promise.promise.promiseDispatch (/home/jifeon/projects/bnsf-adwiki/node_modules/bem/node_modules/q/q.js:760:13)

It's really impossible to guess what the file I should fix for successful build. Could you provide more verbose output with the bemhtml file name?

Inliner ignores iif inside while statements

    while (i__$104 < l__$103) (function __$lb__$107() {
        var __$r__$108;
        var __$l0__$109 = __$ctx.ctx;
        __$ctx.ctx = v__$102[i__$104++];
        __$r__$108 = applyc(__$ctx, __$ref);
        __$ctx.ctx = __$l0__$109;
        return __$r__$108;
    })();

Immediately invoked functions inside while don't get inlined.

Syntax sugar for `applyCtx` with old `thix.ctx` inside

We need some syntax sugar for cases like that:

block('b1').def().match(function() { return !this._wrapped })(function() {
    apply(
        '',
        { 'ctx._wrapped': true },
        { ctx: { block: 'wrap', content: this.ctx } }
    )
})

With applyCtx sugar for assignments it can be written like that:

block('b1').def().match(function() { return !this._wrapped })(function() {
    applyCtx(
        { block: 'wrap', content: this.ctx },
        { 'ctx._wrapped': true }
    )
})

but we still need something for guard !this._wrapped.

An mistake in the wrap method?

I think, instead of

'(function(g) {\n' +
         '  var __bem_xjst = function(exports' + modulesProvidedDeps + ') {\n' +
         '     ' + code + ';\n' +
         '     return exports;\n' +
         '  }\n' +
         '  var defineAsGlobal = true;\n' +
         '  if(typeof exports === "object") {\n' +
         '    exports["' + exportName + '"] = __bem_xjst({}' + modulesProvidedDeps + ');\n' +
         '    defineAsGlobal = false;\n' +
         '  }\n' +
         '  if(typeof modules === "object") {\n' +
         '    modules.define("' + exportName + '"' + modulesDeps + ',\n' +
         '      function(provide' + modulesProvidedDeps + ') {\n' +
         '        provide(__bem_xjst({}' + modulesProvidedDeps + ')) });\n' +
         '    defineAsGlobal = false;\n' +
         '  }\n' +
         '  defineAsGlobal && (g["' + exportName + '"] = __bem_xjst({}' + modulesProvidedDeps + '));\n' +
         '})(this);'

we should use

'(function(g) {\n' +
         '  var __bem_xjst = function(exports' + modulesProvidedDeps + ') {\n' +
         '     ' + code + ';\n' +
         '     return exports;\n' +
         '  }\n' +
         '  var defineAsGlobal = true;\n' +
         '  if(typeof modules === "object") {\n' +
         '    modules.define("' + exportName + '"' + modulesDeps + ',\n' +
         '      function(provide' + modulesProvidedDeps + ') {\n' +
         '        provide(__bem_xjst({}' + modulesProvidedDeps + ')) });\n' +
         '    defineAsGlobal = false;\n' +
         '  }\n' +
         '  else if(typeof exports === "object") {\n' +
         '    exports["' + exportName + '"] = __bem_xjst({}' + modulesProvidedDeps + ');\n' +
         '    defineAsGlobal = false;\n' +
         '  }\n' +
         '  defineAsGlobal && (g["' + exportName + '"] = __bem_xjst({}' + modulesProvidedDeps + '));\n' +
         '})(this);'

because now we force users of bemhtml/bemtree to use global variables in node.js context.

Remove ometa from deps

It seems that there's no use of ometa anymore so it can be safely removed from package.json?

Incorrect processing of mixes

In 2.x branch for BEMJSON

{ block: 'b1', elem: 'e1' }

and template

block('b1').elem('e1').mix()([{
    { block: 'b2' },
    { block: 'b3' }
}]);

the result is

<div class="b1__e1 b2__e1 b3__e1"></div>

Expected

<div class="b1__e1 b2 b3"></div>

Use fat arrow syntax for matchers and templates

As some kind of theoretical thought about current BEMHTML's JS-syntax

Why not to use ES6's arrow functions in our templates? We could pass BEMContext's instance as a first parameter of templates body (bem parameter in the example below) instead of using this keyword.

For example our bem-components' button template could look like this

block('button')(
    def()((bem) => {
        var mods = bem.mods;
        applyNext({ _button : bem.ctx });
    }),

    tag()((bem) => bem.ctx.tag || 'button'),

    js()(true),

    mix()({ elem : 'control' }),

    attrs()(
        // Common attributes
        (bem) => {
            var ctx = bem.ctx,
                attrs = { role : 'button' };

            ctx.tabIndex && (attrs.tabindex = ctx.tabIndex);

            return attrs;
        },

        // Attributes for button variant
        match((bem) => !bem.mods.type)((bem) => {
            var ctx = bem.ctx, attrs = {};

            ctx.tag || (attrs.type = ctx.type || 'button');

            ctx.name && (attrs.name = ctx.name);
            ctx.val && (attrs.value = ctx.val);
            bem.mods.disabled && (attrs.disabled = 'disabled');

            return bem.extend(applyNext(), attrs);
        })
    ),

    content()(
        (bem) => {
            var ctx = bem.ctx, content = [bem.ctx.icon];
            ctx.text && content.push({ elem : 'text', content : ctx.text });
            return content;
        },
        match((bem) => typeof bem.ctx.content !== 'undefined')((bem) => bem.ctx.content)
    )
)

Debug information, asserts, `include`

  • Keep information about input source files (there could be multiple of them) #108 #136
  • Consider adding include
  • lint mode? With assertions for popular mistakes: bemhint/bemhint#56
    • .tag().def().content()
    • .def()(function() { /* forgot to return */ applyCtx({ ... }) })
    • block('b1')(tag()('a')) should be block('b1').tag()('a')

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.