current position:Home>Detailed explanation of art template engine

Detailed explanation of art template engine

2022-05-15 07:44:36Sugar ^ o^


🧨1. Introduce

https://github.com/aui/art-template

It uses scope pre declaration to optimize template rendering speed , So as to get close to JavaScript Extreme operating performance , And at the same time support nodejs And browser

1.1. characteristic

The template engine is a third-party module , Let developers splice strings in a more friendly way , Yes, the code is clearer , Easier to maintain

1.2. Templates

art-template Both syntax are supported , Standard syntax makes templates easier to read and write ,
Primitive grammar has powerful logical processing ability

Standard grammar

{
    {
    if user}}
  <h2>{
    {
    user.name}}</h2>
{
    {
    /if}}

Original grammar

<% if (user) {
     %>
  <h2><%= user.name %></h2>
<% } %>
1.3. Apply colours to a drawing template
var template = require('art-template');
var html = template(__dirname + '/tpl-user.art', {
    
    user: {
    
        name: 'y'
    }
});
1.4. The core approach
//  Render a template based on the template name 
template(filename, data);

//  Compile the template source code into functions 
template.compile(source, options);

//  Compile the template source code into a function and execute immediately 
template.render(source, data, options);

🧨2. install

2.1.npm
npm install art-template --save
2.2. Compile in real time in browser

    <div id="content">
    </div>
    <!--  If you render the template , The data set transmitted is user data , Then display in the page h2 label ,h2 Inside the tag is the user's name  -->
    <script id="demo" type="text/html"> {
      {
      if user}} <h2>{
      {
      user.name}}</h2> {
      {
      /if}} <% if (user) {
       %> <h2><%= user.name %></h2> <% } %> <h1>{
      {
      title}}</h1> <ul> <!-- {
      {
      each list as value i}} <li> Indexes {
      {
      i+1}}:{
      {
      value}}</li> {
      {
      /each}} --> {
      {
      each list}} <li> Indexes {
      {
      $index+1}}:{
      {
      $value}}</li> {
      {
      /each}} </ul> </script>
    <script> var html = template("demo", {
       title: " I'm the title ", user: {
       name: " Zhang San " }, list:[" Zhang San "," Li Si "," Wang Wu "," Horse six "] }) document.getElementById("content").innerHTML = html </script>

🧨3. grammar

art-template Support standard grammar and original grammar . Standard syntax makes templates easy to read and write , The original grammar has a strong logical expression ability .

Standard syntax supports basic template syntax and basic JavaScript expression ; The original syntax supports arbitrary JavaScript sentence , This sum ejs equally .

3.1. Output

Standard grammar

{
   {value}}
{
   {data.key}}
{
   {data['key']}}
{
   {a ? b : c}}
{
   {a || b}}
{
   {a + b}}

Original grammar

<%= value %>
<%= data.key %>
<%= data['key'] %>
<%= a ? b : c %>
<%= a || b %>
<%= a + b %>

Template level special variables can use $data Subscript to access :

{
   {$data['user list']}}
3.2. Original output

Standard grammar

{
   {@ value }}

Original grammar

<%- value %>

The original output statement will not be correct for HTML Escape the content , There may be security risks , Please use with caution .

3.3. Conditions

Standard grammar

{
   {if value}} ... {
   {/if}}
{
   {if v1}} ... {
   {else if v2}} ... {
   {/if}}

Original grammar

<% if (value) { %> ... <% } %>
<% if (v1) { %> ... <% } else if (v2) { %> ... <% } %>
3.4. loop

part2_syntax/app.js/ loop

Standard grammar

{
   {each target}}
    {
   {$index}} {
   {$value}}
{
   {/each}}

Original grammar

<% for(var i = 0; i < target.length; i++){ %>
    <%= i %> <%= target[i] %>
<% } %>
  1. target Support array And object Iteration , The default value is $data.
  2. $value And $index You can customize :{ {each target val key}}.
3.5. Variable

Standard grammar

{
   {set temp = data.sub.content}}

Original grammar

<% var temp = data.sub.content; %>
3.6. Template inheritance
//  Standard grammar 
{
    {
    extend './layout.art'}}
{
    {
    block 'head'}} ... {
    {
    /block}}
///  Original grammar 
<% extend('./layout.art') %>
<% block('head', function(){ %> ... <% }) %>

Template inheritance allows you to build a basic template that contains common elements of your site “ skeleton ”.

Rendering index.art after , The layout skeleton is automatically applied .

3.7. Sub template

. data The default value of the number is $data; The standard syntax does not support declarations object And array, Only reference variables are supported , The original syntax is unrestricted .
Standard grammar

{
   {include './header.art'}}
{
   {include './header.art' data}}

Original grammar

<% include('./header.art') %>
<% include('./header.art', data) %>
3.8. filter

Registration filter

template.defaults.imports.dateFormat = function(date, format){/*[code..]*/};

template.defaults.imports.timestamp = function(value){return value * 1000};

The first parameter of the filter function accepts the target value .

Standard grammar

{
   {date | timestamp | dateFormat 'yyyy-MM-dd hh:mm:ss'}}

{ {value | filter}} The filter syntax is similar to the pipe operator , Its last output is the next input .

Original grammar

<%= $imports.dateFormat($imports.timestamp(date), 'yyyy-MM-dd hh:mm:ss') %>

4. debugging

template.defaults.debug

art-template Built in debugger , Can catch syntax and running errors , And support custom Syntax .

stay NodeJS The debugging mode in will be automatically turned on according to the environment variables :process.env.NODE_ENV !== 'production'

 Set up  `template.defaults.debug=true`  after , Equate to :
{
    "cache": false,
    "minimize": false,
    "compileDebug": true
}

5. Template variable

template.defaults.imports

The template passes $imports You can access global variables outside the template and imported variables .


//  Import the variables 
template.defaults.imports.log = console.log;
<% $imports.log('hello world') %>

List of built-in variables

  • $data Data passed into the template
  • $imports Externally imported variables and global variables
  • print String output function
  • include Sub template loading function
  • extend The template inherits the template import function
  • block Template block declaration function

6. Parsing rules

art-template You can customize template resolution rules , The original syntax and standard syntax are configured by default .

Modify delimiter

//  The delimiter rules of the original grammar 
template.defaults.rules[0].test = /<%(#?)((?:==|=#|[=-])?)[ \t]*([\w\W]*?)[ \t]*(-?)%>/;

//  Delimiter rules of standard grammar 
template.defaults.rules[1].test = /{
   {([@#]?)[ \t]*(\/?)([\w\W]*?)[ \t]*}}/;

They are a regular expression , You can only modify the delimiter part . For example, modify <%%> by <??>

var rule = template.defaults.rules[0];
rule.test = new RegExp(rule.test.source.replace('<%', '<\\\?').replace('%>', '\\\?>'));

among test Is the matching string ,use Is the calling function after matching .

About use function :

  • Parameters : One parameter is the matching string , The remaining parameters are received in turn test Regular grouping matching content

  • Return value : An object must be returned , contain code And output

    Two fields :

    • code Converted JavaScript sentence

    • output describe code The type of , Optional value :

      • 'escape' Output after coding
      • 'raw' Output the original content
      • false Don't output anything

7. Compressed page

template.defaults.minimize

art-template The built-in compressor can compress HTML、JS、CSS, It runs during the compilation phase , So it doesn't affect the rendering speed at all , And can speed up network transmission .

Turn on

template.defaults.minimize = true;

To configure

See :https://github.com/kangax/html-minifier

The default configuration

template.defaults.htmlMinifierOptions = {
    collapseWhitespace: true,
    minifyCSS: true,
    minifyJS: true,
    //  Automatically merge at run time :rules.map(rule => rule.test)
    ignoreCustomFragments: []
};

8.API

8.1.template(filename, content)

Render the template according to the template name .

  • Parameters :

    (1) {string} filename
    (2) {Object,string} content

  • Return value :

    (1) If content by Object, Render the template and return string
    (2) If content by string, Then compile the template and return function

The browser version cannot load external files ,filename To store the elements of the template id

8.2. .compile(source, options)

Compile the template and return a rendering function .

  • Parameters

    (1){string} source
    (2) {Object} options

  • Return value :{function}

Example

var render = template.compile('hi, <%=value%>.');
var html = render({value: 'aui'});
8.3. .render(source, data, options)

Compile and return rendering results .

  • Parameters

    • {string} source
    • {Object} options
  • Return value {string}

Example

var html = template.render('hi, <%=value%>.', {value: 'aui'});

.defaults

The template engine is configured by default . Reference resources Options .

  • type {Object}
8.4. .extension

to NodeJS require.extensions Registered template rendering function .

  • type {Object}

Example

load .ejs Templates :

var template = require('art-template');
require.extensions['.ejs'] = template.extension;

var view = require('./index.ejs');
var html = view(data);

.art Registered by default , You can use it directly :

var template = require('art-template');
var view = require('./index.art');
var html = view(data);

It should be noted that : This function is only available for NodeJS take effect

9.express-art-template

  • In order to make art-template Template engine can be better and Express Frame fit , Template engine official in the original art-template The template engine encapsulates express-art-template.

  • Use npm install art-template express-art-template Command to install .

  • You can use multiple template engines in a project

    express Of engine() Method : When the rendering suffix is art When using the template of express-art-template

The suffix is the first parameter of the template

The second parameter is what template to use

express Of set() Method :

  1. Set the template storage directory

​ (1) The first parameter is to set the folder where the template directory is stored

​ (2) The second parameter is the absolute path to store the template

  1. Set the default template suffix , When setting template , If no template suffix is written, the currently set template suffix will be used

​ (1) The first parameter is Configuration items of the default template

​ (2) The second parameter is the name of the suffix

express Of render() Method :

Apply colours to a drawing template ( Suffixes are automatically spliced inside the method 、 Splicing of template and data 、 Send the result to the client accordingly )

  • The parameter is the template name .
  • object , namely Data passed to the template
//  introduce express frame 
const express = require('express');
//  Introduce the path module 
const path = require('path');
//  Create a server web site  
const app = express();

// 1.  tell express What template engine does the framework use to render template files with what suffix 
app.engine('art',require('express-art-template'))


// 2.  tell express What is the location of the frame template 
//  first views Is constant , yes express Configuration item name for , tell express Storage location of frame formwork 
//  the second views It's the name of the folder 
app.set('views',path.join(__dirname,'views'))
// 3.  tell express What is the default suffix for framework templates  (  Convenient for rendering templates , Omit suffix  )
app.set('view engine','art');
//  Create a route 
app.get('/index',(req,res) => {
    
    //  Apply colours to a drawing template  ( You can get rid of art) -- res.render()
    // 1. Splicing template path 
    // 2. Splice template suffix 
    // 3. Which template and which data are spliced 
    // 4. Respond the splicing result to the client 
    res.render('index',{
    
        //  The data to be displayed in the template 
        msg: 'message'
    })
})

app.get('/list',(req,res) => {
    
    res.render('list',{
    
        msg: 'list page'
    })
})

//  Listening port 
app.listen(3000);

copyright notice
author[Sugar ^ o^],Please bring the original link to reprint, thank you.
https://en.chowdera.com/2022/131/202205102122176545.html

Random recommended