Escape JavaScript quotes in EL in a JSF component attribute

我的未来我决定 提交于 2019-12-28 04:34:05

问题


I have an onclick event that depends on the state of a variable. So I need to do something like

onclick="#{object.isEnabled ? 'ch.my.js_method('#{object.property}'); return false;' : 'return false;'"

The problem is, that I can't use ' inside of the onclick. How can I escape the quotes inside of the EL?


回答1:


You can escape them with \ or \\, but rules differ per EL implementation, because it isn't clear cut in EL spec (Oracle's EL impl needs single backslash, but Apache needs double backslash). And you need the += operator to string-concatenate the EL expression.

<x:someComponent onclick="#{object.isEnabled ? 'ch.my.js_method(\'' += object.property += '\'); return false;' : 'return false;'}" />

Safest bet is to just create an alias with help of <c:set>.

E.g.

<c:set var="js_method" value="ch.my.js_method('#{object.property}'); return false;" />
<x:someComponent onclick="#{object.isEnabled ? js_method : 'return false;'}" />

You've only still a potential problem if #{object.property} can contain JS-special characters which can in turn cause invalid JS output, such as single quotes or newlines. Head to the second link below for the solution to that.

See also:

  • How to concatenate Strings in EL expression?
  • How do I pass JSF managed bean properties to a JavaScript function?



回答2:


I found another solution: just invert the condition and add the event afterwards. This way the quotes around the JS method are not needed:

onclick="#{object.isEnabled == 'false' ? 'return false;' : ''} ch.my.js_method('#{object.property}'); return false;"



来源:https://stackoverflow.com/questions/33019729/escape-javascript-quotes-in-el-in-a-jsf-component-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!