How to access parent attribute in a nested JSP Tag File?
Asked Answered
A

2

7

I must be blind or using the wrong search terms because I cannot find a good answer on this.

I have two custom JPS tag files. One will be nested within the other one. How can I access an attribute in the parent tag from inside the child tag?

One workaround is to add add a variable to request scope, but I'm not loving this option and it might cause some problems. Is there's a more straightforward option?

Thanks!

<%-- OuterTag.tag --%>
--------------------------------------
<%@tag %>
<%@attribute name="color" required="true" %>
<c:set var="color" value="${color}" scope="request" /> <%-- I'm trying to avoid doing this --%>
<div>
   <jsp:doBody/>
</div>


<%-- InnerTag.tag --%>
--------------------------------------
<%@tag %>
<p style="background-color: ${parent.color}"/> <%-- I want to do something like this --%>



<%-- Example Usage --%>
--------------------------------------
<custom:OuterTag color="red">
    <custom:InnerTag/>
    <custom:InnerTag/>
    <custom:InnerTag/>
</custom:OuterTag>
Automat answered 9/6, 2014 at 19:24 Comment(1)
No takers? Was this a dumb question? Seems like it should be so simple. I thought it would be answered within 15 minutes. lolAutomat
B
0

What you are trying do here is perfectly logical - and that what custom tags and tag files should allow us achieve. This behavior is implementation based - and has been fixed on Apache see here. What container are you using ? I have run into similar issue in Jetty, and filed another bug which has been acknowledged, but not yet addressed.

Batory answered 29/9, 2014 at 12:38 Comment(0)
G
0

You can find your parent tag using:

ParentTag parent = (ParentTag)findAncestorWithClass(this, ParentTag.class);

Then, you can have public methods on the parent the children can use to interact with it.

Take a look at this URL for further details: http://www.informit.com/articles/article.aspx?p=26119&seqNum=9

Goldy answered 3/6, 2016 at 12:51 Comment(1)
This works only for full-fledged custom tags, not tag files that the OP is using or asking about.Monolatry

© 2022 - 2024 — McMap. All rights reserved.