使用<image src =“ @ routes.Assets.at(” public / images“,” logo.png“)”>检查图像是否存在

dsr*_*301 3 playframework playframework-2.0

在playframework加载图像我正在使用@ routes.Assets.at

喜欢

但是我只想在此logo.png可用的情况下加载此图像。因为在没有图像的情况下,它显示为空的图像空间。

有没有类似的语法

@ routes.Assets.at(“ public / images”,“ logo.png”)。getorelse()的类型为..,但是返回类型不是此处的type选项。

Sch*_*rdt 5

我怀疑您的方法是否正确,因为图像需要宽度,高度和alt属性。如果您拥有该数据,则应该已经知道该图像存在。

您可以创建模板img.scala.html:

@(path: String, width: Int, height: Int, alt: String = "")

@import play.api.Play.resource
@import play.api.Play.current

@if(resource("public/" + path).isDefined) {
    <img src="@routes.Assets.at(path)" width="@width" height="@height" alt="@alt"/>
}
Run Code Online (Sandbox Code Playgroud)

并以这种方式使用它:

<hr>
@img("images/favicon.png", 16, 16, "play framework logo")
<hr>
@img("images/not-existing.png", 16, 16, "foo bar")
<hr>
Run Code Online (Sandbox Code Playgroud)

因此它将导致:

<hr>
<img src="/assets/images/favicon.png" width="16" height="16" alt="play framework logo"/>
<hr>
<hr>
Run Code Online (Sandbox Code Playgroud)

项目:https//github.com/schleichardt/stackoverflow-answers/tree/so18605473