gpt4 book ai didi

grails - 在Grails自定义标签库中查找父标签

转载 作者:行者123 更新时间:2023-12-02 16:00:52 25 4
gpt4 key购买 nike

我正在Grails中开发自定义taglib,应该知道父标记。因此,如果我在GSP中有这样的内容:

<a href="#">
<my:tag blabla="blabla"/>
</a>

那么my:tag的实现应该能够发现它包含在标签'a'内,而不是其他内容。
那么这可能会:
1.找出哪个标签是父标签?
2.更改父标签属性?

最佳答案

编辑-此处的答案未按要求回答问题。请参阅注释以获取解释。我将答案留在这里,因为删除它会使所有其他注释变得难以理解,但是这里的答案不是所问问题的有效答案。很抱歉听到这个声音。

改变父标签属性不是一个好方法,但是这绝对不是一个好主意。几乎可以肯定,有一种更好的方法可以完成使您想要执行的操作。但是,想知道一个标签是否嵌套在另一个特定的标签中是一件很合理的事情,并且有很简单的方法可以做到。一种方法是,您的父标记可以在pageScope中存储某些状态,而子标记可以查询该值以确定是否在父内部调用它。您可以只使用 bool(boolean) 标志,但是如果您担心嵌套的多个级别,那将是有问题的。计数器可以跟踪任意深度。

像下面这样的东西应该起作用。

TagLib:

// grails-app/taglib/demo/DemoTagLib.groovy
package demo

class DemoTagLib {

static namespace = 'demo'

def someParentTag = { attrs, body ->
def depthCounter = pageScope.someParentTagDepthCounter ?: 0
pageScope.someParentTagDepthCounter = ++depthCounter

out << body()

pageScope.someParentTagDepthCounter = --depthCounter
}

def someChildTag = { attrs, body ->
// This tag will only render its body if the tag invocation
// is nested inside of a someParentTag parent. This just
// demonstrates one way that a tag can discover if it is
// nested inside of some other specific tag.
if(pageScope.someParentTagDepthCounter) {
out << body()
}
}
}

单元测试:
// src/test/groovy/demo/DemoTagLibSpec.groovy
package demo

import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(DemoTagLib)
class DemoTagLibSpec extends Specification {

void "test something"() {
expect: 'when someChildTag is not wrapped in someParentTag then the someChildTag body is not rendered'
applyTemplate('Heading <demo:someChildTag>Body</demo:someChildTag>') == 'Heading '

and: 'when someChildTag is wrapped in someParentTag then the someChildTag body is rendered'
applyTemplate('Heading <demo:someParentTag><demo:someChildTag>Body</demo:someChildTag></demo:someParentTag>') == 'Heading Body'

and: 'when multiple someChildTags are nested in multiple levels of someParentTags, their bodies are rendered'
applyTemplate('Heading <demo:someParentTag><demo:someChildTag>First Child<demo:someParentTag> <demo:someChildTag>Second Child</demo:someChildTag></demo:someParentTag></demo:someChildTag></demo:someParentTag>') == 'Heading First Child Second Child'
}
}

希望对您有所帮助。

关于grails - 在Grails自定义标签库中查找父标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31076959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com