从Grails Tablib返回布尔值?

从Grails Tablib返回布尔值?,grails,gsp,Grails,Gsp,我创建了一个自定义Grails tablib: def hasRole = { attrs, body -> boolean result = false if (attrs.roles) { if (SpringSecurityUtils.ifAnyGranted(attrs.roles)) { result = true } } out << result } 问题是比较结果总是yes。

我创建了一个自定义Grails tablib:

  def hasRole = { attrs, body ->
    boolean result = false 
    if (attrs.roles) {
      if (SpringSecurityUtils.ifAnyGranted(attrs.roles)) {
        result = true
      }
    }
    out << result  
  }
问题是比较结果总是
yes
。这表明表达式的计算结果不正确

hasRole的返回类类型是
org.codehaus.groovy.grails.web.util.StreamCharBuffer


如何正确计算上述表达式,以使
hasRole()
返回布尔值?

关键是在标记库中使用
returnObjectForTags
。默认情况下,标记库将信息输出到输出编写器(
out
)。在您的情况下,您希望执行以下操作:

package example

class FooTagLib {
  static namespace = 'something'
  static returnObjectForTags = ['hasRole']

  def hasRole = { attrs, body ->
    boolean result = false
    ...
    return result
  }
}

正如您所看到的
returnObjectForTags
是一个静态的方法/闭包列表,您希望为这些方法/闭包返回实际的对象,并且不希望直接修改输出流。

非常有效!谢谢
package example

class FooTagLib {
  static namespace = 'something'
  static returnObjectForTags = ['hasRole']

  def hasRole = { attrs, body ->
    boolean result = false
    ...
    return result
  }
}