Grails 标签中的默认正文行为



我正在尝试实现一个标签,如果没有作为参数传递,则必须呈现默认正文。这是我的第一次尝试:

def myDiv = { attrs, body ->
  out << '<div class="fancy">'
  if (body) //this approach doesn't work cause body is a closure that is never null
     out << body()
  else
     out << 'default content'
  out << '</div>'
}

然后我们将有 2 个简单的使用场景。

1) <g:myDiv/> 内容正文不存在,应呈现:

<div class="fancy">
   default content
</div>

2) <g:myDiv> SPECIFIC content </g:myDiv>内容正文存在,应呈现:

<div class="fancy">
   SPECIFIC content
</div>

在这种情况下,最好的方法是什么?

我在tagLib中打印出了"body"类以了解更多信息。

println body.getClass() // outputs: class org.codehaus.groovy.grails.web.pages.GroovyPage$ConstantClosure

这是一个GroovyPage.ConstantClosure

当您检查您的状况中的"身体"时,它是一个闭合。如果你使用单个标签<g:tester/>那么正文似乎不存在,你可以使用 ConstantClosure 的 asBoolean(),它会返回 false。

def tester = {attrs, body ->
  println body.asBoolean()  // prints: false
  if (body) {
    println "body"
  } else {
    prinltn "no body"
  }
}
// outputs : "no body"

当我使用两个标签时<g:tester></g:tester>输出是"body"所以我尝试了以下内容:

def tester = {attrs, body ->
  println "**$body**"      // prints:  **
                           //          **
  println body.asBoolean() // prints:  true
  println body().size()    // prints:  1
}

我猜正文包含一些返回字符或空格。

我最好的解决方案是调用该方法body()这将返回一个 String,您可以调用它trim()并在具有时髦真理的情况下检查它

def tester = {attrs, body ->
  if (body().trim()) {
    println "body"
  } else {
    println "no body"
  }
}  // outputs : "no body" in all scenarios except when body contains something relevant.

最新更新