在安全Html模板中设置背景图像URL

时间:2013-05-02 01:07:49

标签: gwt

我有以下代码,我想在其中创建一个具有动态背景的div

public interface Template extends SafeHtmlTemplates {
    @Template("<div class='imageDiv' style=\"background-image: url({0});\"/>")
    SafeHtml content(String picture);
}

public void render(SafeHtmlBuilder safeHtmlBuilder, final T model) {
    SafeHtml html = TEMPLATE.content(picture);
    safeHtmlBuilder.append(html);
}

运行应用程序后,首先我收到了此警告:

Template with variable in CSS attribute context: 
The template code generator cannot guarantee HTML-safety of the template

然后出错:

java.lang.NullPointerException: null
at com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(SafeHtmlUtils.java:156)
at xx.xx.xx.xx.xx.ImageItemCell_TemplateImpl.content(ImageItemCell_TemplateImpl.java:14)
at xx.xx.xx.xx.xx.ImageItemCell.render(ImageItemCell.java:53)

当我尝试将图片设置为SafeUri时:

SafeUri uri = UriUtils.fromTrustedString(picture);
SafeHtml html = TEMPLATE.content(uri);

我得到了这个不同的错误:

 [ERROR] - SafeUri can only be used as the entire value of a URL attribute. 
          Did you mean to use java.lang.String or SafeHtml instead?

在这种情况下我该怎么做?

感谢。

1 个答案:

答案 0 :(得分:1)

您必须使用SafeStyles

public interface Template extends SafeHtmlTemplates {
    @Template("<div class='imageDiv' style='{0}'></div>")
    SafeHtml content(SafeStyles picture);
}

public void render(SafeHtmlBuilder safeHtmlBuilder, final T model) {
    SafeHtml html = TEMPLATE.content(SafeStyleUtils.forBackgroundImage(picture));
    safeHtmlBuilder.append(html);
}

(假设picture此处为SafeUri