简体   繁体   English

JavaScript模板引擎-将左三元(无赋值)转换为条件语句

[英]JavaScript templating engine - Converting left hand ternary (without an assignment) into conditional statement(s)

I've found the perfect JavaScript templating engine, built by Krasimir, it is just what I needed. 我发现了由Krasimir构建的完美的 JavaScript模板引擎,这正是我所需要的。
The templating engine works great but naturally I couldn't resist the urge to hack at it a bit and maybe even add a couple of features. 模板引擎效果很好,但是自然地我忍不住想要破解它的冲动,甚至可能添加了一些功能。
Unfortunately I am having trouble understanding some of the code. 不幸的是,我在理解某些代码时遇到了麻烦。

Here is the code: 这是代码:

var TemplateEngine = function(html, options) {
  var re = /<%([^%>]+)?%>/g,
    reExp = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g,
    code = 'var r=[];\n',
    cursor = 0,
    match;
  var add = function(line, js) {
    /* --begin problem  */
    js ? (code += line.match(reExp) ? line + '\n' : 'r.push(' + line + ');\n') : (code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');
    /* --end problem    */
    return add;
  };
  while (match = re.exec(html)) {
    add(html.slice(cursor, match.index))(match[1], true);
    cursor = match.index + match[0].length;
  }
  add(html.substr(cursor, html.length - cursor));
  code += 'return r.join("");';
  return new Function(code.replace(/[\r\t\n]/g, '')).apply(options);
};

Here is the line I don't understand: 这是我不明白的那一行:

js ? (code += line.match(reExp) ? line + '\n' : 'r.push(' + line + ');\n') : (code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');

I'm not new to JavaScript but that's some weird looking code and from what I know it is a ternary operator without a left hand assignment (correct me if I'm wrong) 我对JavaScript并不陌生,但这是一些看起来很奇怪的代码,据我所知,它是没有左手分配的三元运算符(如果我错了,请纠正我)

So in order to get a better understanding of what the author was doing I have attempted to convert the ternary operator into conditional statements. 因此,为了更好地了解作者在做什么,我尝试将三元运算符转换为条件语句。

This is what I have so far: 这是我到目前为止的内容:

if(js) {
  if(code += line.match(reExp)) {
    line += '\n';
  } else {
    line += 'r.push(' + line + ');\n';
  }
} else {
  if(code += line !== '') {
    line += 'r.push("' + line.replace(/"/g, '\\"') + '");\n';
  } else {
    line += "";
  }
}

This failed and threw the error "Uncaught SyntaxError: Unexpected token if" 这失败并抛出错误“ Uncaught SyntaxError:如果出现意外令牌”

Can anybody help me convert this code into conditional statements and maybe even give me an explanation as to what the code does? 谁能帮助我将此代码转换为条件语句,甚至可以给我解释代码的作用吗?

Also out of curiosity could anybody tell me if IE8 supports this code? 另外出于好奇,有人可以告诉我IE8是否支持此代码?
NOTE: I don't mind IE8 support I would just like to know if this templating engine supports IE8. 注意:我不介意IE8支持,我只想知道此模板引擎是否支持IE8。

You can find the templating engine on Krasimir's Website or Krasimir's Github 您可以在Krasimir的网站或Krasimir的Github上找到模板引擎

You are not supposed to append code to line you must append to code, try this: 您不应该将代码追加到行中,而必须追加到代码中,请尝试以下操作:

if (js && type(js) !== "undefined") {
  if (line.match(reExp)) {
    code += line;
  } else {
    code += "r.push(" + line + ");";
  }
} else if (line !== "") {
  code = code + "r.push(\"" + line.replace(/"/g, '\\"') + "\");";
}

The ternary operator ?: works in JavaScript just like in C. In this case, we can format the expression as 三元运算符?:就像C中一样在JavaScript中工作。在这种情况下,我们可以将表达式格式化为

js? (code += (line.match(reExp)? line + '\n' : 'r.push(' + line + ');\n')
  : (code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');

and it looks just like an if-else block. 它看起来就像一个if-else块。 The whole expression evaluates to one of two compound assignment expressions, depending on the value of js . 整个表达式的计算结果为两个复合赋值表达式之一,具体取决于js的值。 The value of this expression is ignored, but we can still get side-effects out of it. 该表达式的值被忽略,但是我们仍然可以摆脱它的副作用。 The author simply chose to write this instead of if (js) { code += ...; } else { code += ...; } 作者只是选择编写此if (js) { code += ...; } else { code += ...; }而不是if (js) { code += ...; } else { code += ...; } if (js) { code += ...; } else { code += ...; } if (js) { code += ...; } else { code += ...; } . if (js) { code += ...; } else { code += ...; }

I know this question has not gotten a lot of attention but I thought I'd post this answer anyways in hopes that it would help someone who is facing this problem. 我知道这个问题并没有引起足够的重视,但我想我还是会发布此答案,以希望对遇到此问题的人有所帮助。
With some effort and a ton of help from JSHint I have figured out the solution to my question. 经过JSHint的不懈努力和大量帮助,我终于找到了解决我问题的方法。
I was appending the current compiled line to the "line" variable and not the "code" variable. 我将当前已编译的行附加到“ line”变量而不是“ code”变量。
This resulted with the "line" variable containing the last line of the template and the rest of the compiled code, meaning that the "code" variable had no code :D and was therefor equivalent to null . 结果是“ line”变量包含模板的最后一行和其余已编译的代码,这意味着“ code”变量没有code :D ,因此等于null

Here is the code I had before I figured out what I was doing wrong: 这是我弄清楚自己做错了什么之前的代码:

var add = function(line, js) {
  if(js) {
    if(code += line.match(reExp)) {
      line += '\n';
    } else {
      line += 'r.push(' + line + ');\n';
    }
  } else {
    if(code += line !== '') {
      line += 'r.push("' + line.replace(/"/g, '\\"') + '");\n';
    } else {
      line += "";
    }
  }
};

After replacing the "line" variable with the "code" variable here and there and making a couple of optimisations here is the final working answer: 在将“ line”变量替换为“ code”变量之后,在此处进行了一些优化,这是最终的工作答案:

var add = function(line, js) {
  if(js && typeof js !== "undefined") {
    if(line.match(reExp)) {
      code += line;
    } else {
      code += "r.push(" + line + ");";
    }
  } else if(line !== "") {
    code += "r.push(\"" + line.replace(/"/g, '\\"') + "\");";
  }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM