【问题标题】:Conditional render in tagfile depending on whether the attribute is specified or not标签文件中的条件渲染取决于是否指定了属性
【发布时间】:2026-02-13 05:35:01
【问题描述】:

我有一个 Facelet 标记文件,需要根据是否指定属性来呈现不同的组件。我试过如下,

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:p="http://primefaces.org/ui"
    xmlns:pe="http://primefaces.org/ui/extensions"
    xmlns:c="http://java.sun.com/jsp/jstl/core">

    <h:panelGrid columns="1">
        <p:outputLabel value="test1" rendered="#{empty myParam}" />
        <p:outputLabel value="test2" rendered="#{not empty myParam}" />
    </h:panelGrid>
</ui:composition>

如下使用,

<mt:myTag myParam="#{myManagedBean.someProperty}" />

但是,它没有用。它采用#{myManagedBean.someProperty} 的评估值。如果它是空的,那么它仍然显示test1。如何检查myParam 属性是否实际被设置?

【问题讨论】:

    标签: jsf-2 attributes facelets tagfile conditional-rendering


    【解决方案1】:

    使用 taghandler 类创建另一个自定义标记,该类检查当前 Facelet 上下文的变量映射器中是否存在某个属性,并在 Facelet 范围内设置一个布尔值,指示是否存在所需属性。最后在你的标签文件中使用它。

    例如

    <my:checkAttributePresent name="myParam" var="myParamPresent" />
    <h:panelGrid columns="1">
        <p:outputLabel value="test1" rendered="#{not myParamPresent}" />
        <p:outputLabel value="test2" rendered="#{myParamPresent}" />
    </h:panelGrid>
    

    使用此标签处理程序:

    public class CheckAttributePresentHandler extends TagHandler {
    
        private String name;
        private String var;
    
        public CheckAttributePresentHandler(TagConfig config) {
            super(config);
            name = getRequiredAttribute("name").getValue();
            var = getRequiredAttribute("var").getValue();
        }
    
        @Override
        public void apply(FaceletContext context, UIComponent parent) throws IOException {
            context.setAttribute(var, context.getVariableMapper().resolveVariable(name) != null);
        }
    
    }
    

    在您的.taglib.xml中注册如下:

    <tag>
        <tag-name>checkAttributePresent</tag-name>
        <handler-class>com.example.CheckAttributePresentHandler</handler-class>
        <attribute>
            <name>name</name>
            <required>true</required>
            <type>java.lang.String</type>
        </attribute>
        <attribute>
            <name>var</name>
            <required>true</required>
            <type>java.lang.String</type>
        </attribute>
    </tag>
    

    【讨论】:

      最近更新 更多