Elegant clean way to include HTML in JavaScript files?

后端 未结 7 2147
误落风尘
误落风尘 2020-12-23 10:05

I\'m building a small app with a few modal dialog windows. The windows require a tiny bit of HTML. I\'ve hard coded the window HTML in the javascript library but am not th

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-23 10:54

    For multiline strings (no frameworks, just javascript) there are several solutions. See my answer to this SO Question. You could combine that with some simple templating:

    String.prototype.template = String.prototype.template ||
            function (){
                var  args = Array.prototype.slice.call(arguments)
                    ,str = this
                    ,i=0
                    ;
                function replacer(a){
                    var aa = parseInt(a.substr(1),10)-1;
                    return args[aa];
                }
                return  str.replace(/(\$\d+)/gm,replacer)
    };
    //basic usage:
    'some #1'.template('string'); //=> some string
    //your 'html' could look like:
    var html =
      [ '
    ', '
    ', '
    ', '
    ', '
    ', '
    ', '
    ', '
    ', '
    ', '
    ', '
    ' ] .join('').template(email, subject, body);

提交回复
热议问题