【问题标题】:Conditionally render element's attribute in a composite component有条件地在复合组件中渲染元素的属性
【发布时间】:2012-10-05 12:28:58
【问题描述】:

我有以下复合组件:

<?xml version="1.0" encoding="UTF-8"?>
<ui:component xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:c="http://java.sun.com/jsp/jstl/core"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:p="http://primefaces.org/ui"
    xmlns:fn="http://java.sun.com/jsp/jstl/functions"
    xmlns:composite="http://java.sun.com/jsf/composite">

    <composite:interface>
        <composite:attribute required="true" name="field" />
        <composite:attribute required="true" name="value" />
        <composite:attribute required="false" name="size"/>
    </composite:interface>

    <composite:implementation>
    ...
            <div class="wrapper">
                <h:inputText value="#{cc.attrs.value}"
                    id="#{field.id}" 
                    rendered="#{field.rendered}" 
                    size="#{cc.attrs.size}">
                </h:inputText>
                <h:messages for="#{field.id}" styleClass="errorMessage"/>
            </div>
    ...
    </composite:implementation>
</ui:component>

问题是,当我使用这个组件而不设置其size 属性时,它仍然在html 输入元素中呈现为size=0

我想要的是仅在嵌套h:inputText 的属性具有有效值(例如,不为空)时才呈现它。或者,如果嵌套元素的所有属性没有被显式覆盖,我想公开它们。

这怎么可能?

【问题讨论】:

标签: jsf composite-component


【解决方案1】:

您可以使用 JSTL &lt;c:if&gt; 有条件地构建视图,并使用 &lt;f:attribute&gt; 单独指定属性:

<h:inputText ...>
    <c:if test="#{not empty cc.attrs.size}">
        <f:attribute name="size" value="#{cc.attrs.size}" />
    </c:if>
</h:inputText>

另一种方法是为复合组件属性指定默认值:

<cc:attribute name="size" required="false" default="10" />

【讨论】:

  • 谢谢!它有效,但对我来说很奇怪,如果我直接添加&lt;f:attribute name="size" value="20"/&gt;&lt;f:attribute name="size" value='20'/&gt;,我会得到javax.servlet.ServletException: argument type mismatch,如果我添加&lt;f:attribute name="size" value=20/&gt;,我会得到Open quote is expected for attribute "value"
  • 它必须是Integer,而不是String
  • 是的,但是如何在value 属性中添加Integer?带引号的它被解释为String,不带引号的例外是不同的。
【解决方案2】:

BalusC 帖子的补充:

你必须使用

type="int" 在 cc:attribute-tag 中:

cc:attribute name="maxlength" type="int"

【讨论】:

    【解决方案3】:

    我相信还有另一种访问属性的方法。在访问以 java 保留关键字命名的属性时,我已将其与 JSF 2 一起使用。

    {cc.attrs['size']}

    【讨论】:

      猜你喜欢
      • 2014-08-07
      • 2018-01-24
      • 2020-07-12
      • 2017-12-10
      • 1970-01-01
      • 2020-03-01
      • 2020-04-27
      • 1970-01-01
      • 2022-07-23
      相关资源
      最近更新 更多