Notes on regular expressions (5)

Time:2021-3-5

Template

In the back-end language, there will be corresponding template language support

smarty, blade // php
velocity, freemarker // jsp

However, in the front end, if you want to use the template, you have to do it yourself. At this time, we have to ask outString.replaceThere’s no way.

thinking

  • Constructing regular expressions
  • Define matching rules
  • Replace data

embryonic form

var str = '<div class="{{classname}}"></div>';
var pattern = /\{\{(\w+)?\}\}/g;
str.replace(pattern,function(){
    return 'abc'
})
//'<div class="abc"></div>'

The construction of regular expressions is often determined according to the requirements. How we define the template string will affect the declaration of the regular expression.

Extended practice

Defining regular expressions

var RE_TPL = /\{\{(\w+)?\}\}/g

Define template string

var TPL = {
    Alert: '<div class="win-pop {{clazz}}">'
        +    '<div class="win-t"><div></div></div>'
        +    '<div class="win-con">'
        +        '<div class="win-con-in">'
        +            '<div class="win-box" id="xwb_dlg_ct">'
        +                '{{contentHTML}}'
        +            '</div>'
        +        '</div>'
        +        '<div class="win-con-bg"></div>'
        +    '</div>'
        +    '<div class="win-b"><div></div></div>'
        +'</div>'
}

Define template resolution object

var T = {
    /**
     *[parse template parsing function]
     *@ param {[string]} TPL [template string]
     *@ param {[object]} map [template data]
     *@ return {[string]} [parsed template string]
     */
    parse: function(tpl, map) {
        if (!map) map = {};
        tpl = tpl.replace(RE_TPL, function(m,k){
            var v = map[k] 
            if(v === undefined || v === null)
                return '';
            return v;
        })
        return tpl;
    }
}

T.parse( TPL.Alert , {clazz: "test", contenthtml, "< span > Sweet < / span >"})

Basically, we have implemented a simple JS template.

Requirement change

Sometimes, we need to define other logic in the template, such as judgment, template nesting and so on.

We can define the specific rules by ourselves.

New rules

In order to distinguish the previous template, we try to use a new template qualifier[?xxx?]

var RE_TPLIF = /\[\?(!?)(\w+?)\?([\S\s]*?)\?\]/g;

Extended analytic function

var T = {
    /**
    *Template cache
    * */
    TPLS: {},
    /**
     *[parse template parsing function]
     *@ param {[string]} TPL [template string]
     *@ param {[object]} map [template data]
     *@ return {[string]} [parsed template string]
     */
    parse: function(tpl, map) {
        if (!map) map = {};

        if (tpl.charAt(0) !== '<') {
            var temp = T.TPLS[tpl];
            if (temp)
                tpl = temp;
        }

        tpl = tpl.replace(RE_TPLIF,function(m,s0,s1,s2){
            if (s0 === '!')
                return !map[s1] ? s2: '';
            return map[s1] === undefined ? '' : s2;
        })

        tpl = tpl.replace(RE_TPL, function(m,k){
            var v = map[k] || T.TPLS[k];
            if(v === undefined || v === null) {
                return '';
            }

            if (v.toString().charAt(0) == '<') {
                return T.parse(v,map)
            }

            if (T.TPLS[v]) {
                return T.parse(T.TPLS[v],map)
            }

            return v;
        })
        return tpl;
    },
    /**
     *Object extension
     * @param target
     * @param src
     * @returns {Object}
     */
    extend: function(target,src) {
        target = target || {};
        var i, toString = Object.prototype.toString;
        for (i in src) {
            if (src.hasOwnProperty(i)) {
                if (typeof src[i] === "object") {
                    target[i] = (toString.call(src[i]) === ["object Array"]) ? [] : {};
                    this.extend(src[i], target[i]);
                } else {
                    target[i] = src[i];
                }
            }
        }
        return target;
    },
    /**
     *Initialization template
     * @param map
     */
    set: function(map) {
        this.extend(this.TPLS,map)
    }
}

Next, let’s modify the template to add a judgment for the title.

var TPL = {
    Alert: '<div class="win-pop {{clazz}}">'
        +    '<div class="win-t"><div></div></div>'
        +    '<div class="win-con">'
        +    '[?title?{{Title}}?]'
        +        '<div class="win-con-in">'
        +            '<div class="win-box" id="xwb_dlg_ct">'
        +                '{{contentHTML}}'
        +            '</div>'
        +        '</div>'
        +        '<div class="win-con-bg"></div>'
        +    '</div>'
        +    '<div class="win-b"><div></div></div>'
        +'</div>',
    Title: '< H1 > simple template < / H1 >'
}

setup code

T.set(TPL);

console.log(T.TPLS)

console.log(T.parse(TPL.Alert,{
    clazz: "abc",
    Contenthtml: "< span > Sweet < / span >"
}))

Template explanation

[?title?{{Title}}?]
[? Title? < H1 > simple template < / H1 >?]

Set toT.parseOfmapObject to set the ‘title’ property?

  • Yes, render using the default template{{Title}} => T.Title
  • No, do not render the template

summary

  • Template rules can be customized freely
  • Parsing data through capture grouping of regular expressions

Resource links

http://regexpal.com/
http://regexper.com/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_…
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Glob…

Recommended Today

Deeply analyze the principle and practice of RSA key

1、 Preface After experiencing many dark moments in life, when you read this article, you will regret and even be angry: why didn’t you write this article earlier?! Your darkest moments include: 1. Your project needs to be connected with the bank, and the other party needs you to provide an encryption certificate. You have […]