如何为 Bootstrap 弹出窗口和工具提示内容编码 html

问题描述:

这可能是重复的;很难说,因为关键字包含html"和内容",甚至 Bing 和 Google 都返回了很多误报.

This may be a duplicate; it's hard to tell because the key words contain "html" and "content" and even Bing and Google were returning a lot of false positives.

当 data-html=true 时,Bootstrap 工具提示和弹出框支持 data-content 属性的 html 值.但是,这是无效的

Bootstrap tooltips and popovers support html values for the data-content attribute when data-html=true. However, this isn't valid

<input id="email" class="form-control" type="email" 
  data-bind="value: Email, valueUpdate: 'afterkeydown'" 
  data-container="body" data-toggle="popover" data-placement="bottom"
  data-title="Email" data-html="true"
  data-content="<p>This is <i>your</i> email address.</p>" />

因为您不能将 html 放在本身就是 HTML 的属性的值中.它可能会混淆解析器并且是 HTML 规范不允许的.

because you can't just put html in the value of an attribute that is itself HTML. It may confuse the parser and is not permitted by the HTML specification.

虽然它似乎适用于 Internet Explorer,但我真的不想用 50 种不同的浏览器和版本进行测试.它肯定确实混淆了 Visual Studio 2013 HTML 编辑器中的解析器.那个编辑认为没有结束语.

While it seems to work with Internet Explorer, I really don't feel like testing with fifty different browsers and versions. It certainly does confuse the parser in the Visual Studio 2013 HTML editor. That editor thinks there's no closing quote.

我可以通过在单独的文件中分配来自 JavaScript 的属性来避免这种情况,但这样做很笨拙,而且无法实现关注点分离.

I could dodge this by assigning the attribute from JavaScript in a separate file, but that's clumsy and defeats the separation of concerns.

那么,标记它的正确方法是什么?

So, what's the right way to mark this up?

您可以向 HTML 属性添加任何您想要的内容,只要它是有效的 html 属性值.什么是有效的属性值?什么不包含标签、引号等.所以……然后呢?解决方案是:在将字符串附加到 html 属性之前先对字符串进行转义.

You can add whatever you want to an HTML attribute as long as it is a valid html attribute value. What is a valid attribute value? What does not contains tags, quotes and so on. So.... and what? The solution is: Scape the string before append it inside the html attribute.

如果您使用的是 PHP:http://fi2.php.net/htmlspecialchars或 Twig:http://twig.sensiolabs.org/doc/filters/escape.html

If you are using PHP: http://fi2.php.net/htmlspecialchars Or Twig: http://twig.sensiolabs.org/doc/filters/escape.html

如果你使用 jquery,当你执行 $el.data('my_scaped_json) 时,它会被转换成它原来的样子,比如一个 json 对象或 html 字符串: $( $el.data('my_scaped_html) );

If you are using jquery, when you do $el.data('my_scaped_json) will be converted to whatever it was originally, such a json object or html-string: $( $el.data('my_scaped_html) );