[英]Escape string in elixir
Given a String like str = “\\“
and then rendering it into some other program like JS or Python:给定一个像
str = “\\“
这样的str = “\\“
,然后将它渲染到其他一些程序中,比如 JS 或 Python:
# index.js.eex
console.log(„<%= str %>“)
# hello.py.eex
print(„<%= str %>“)
results in console.log(„\\“)
结果在
console.log(„\\“)
You see the problem the backslash will escape the closing quote and produce a syntax error in JS您会看到反斜杠将转义结束引号并在 JS 中产生语法错误的问题
The question is, How should I fix it?问题是,我应该如何修复它?
PS: I am writing it on a mobile phone, so the quotes are not correct, will fix it as soon I am on my laptop PS:我是在手机上写的,所以引用不正确,我在我的笔记本电脑上会尽快修复
You can "javascript encode" the string in elixir.您可以在 elixir 中对字符串进行“javascript 编码”。
The rules for JS are that a slash needs to be double-escaped. JS 的规则是斜线需要双重转义。 You can do that yourself, or use something like Phoenix.HTML.javascript_escape
你可以自己做,或者使用类似Phoenix.HTML.javascript_escape 的东西
javascript_escape("my string with \\")
If you are using Phoenix you might find these useful https://hexdocs.pm/phoenix_html/Phoenix.HTML.html#escape_javascript/1https://hexdocs.pm/phoenix_html/Phoenix.HTML.html#html_escape/1如果您使用 Phoenix,您可能会发现这些有用https://hexdocs.pm/phoenix_html/Phoenix.HTML.html#escape_javascript/1https://hexdocs.pm/phoenix_html/Phoenix.HTML.html#html_escape/1
Or perhaps convert it to JSON and skip the quotes.或者也许将其转换为 JSON 并跳过引号。 Here's an example.
这是一个例子。
# index.js.eex
console.log(<%= raw(Jason.encode!(str)) %>)
Perhaps a view helper would be better (example for Phoenix):也许视图助手会更好(例如 Phoenix):
defmodule MyAppWeb.LayoutView do
use MyAppWeb, :view
def raw_json(data) do
case Jason.encode(data) do
{:ok, result} -> raw(result)
{:error, _reason} -> nil # Depending on what fallback you want
end
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.