【问题标题】:Auto-generated ids for facelets components为 facelets 组件自动生成的 id
【发布时间】:2011-06-03 22:17:33
【问题描述】:

我们使用 facelets 来创建一些自定义的 ajaxy 组件。我们希望从默认组件中模仿的行为之一是 id 是可选的,如果没有传递,则会生成一个 id。我已经可以这样做了:

<ui:composition ...>
  <div class="myComponent" id="#{jsfSupport.generateId(id)}">
     ...
  </div>
</ui:composition>

我使用 JBoss el 调用支持方法(也可以使用 el 函数):

public class JsfSupport {

  public String generateId(String id) {

    if (id==null || "".equals(id){
  return FacesContext.getCurrentInstance().getViewRoot().createUniqueId();
    }
    return id;
  }

}

问题是,如果我在组件的 javascript 代码中的某处需要该 id,我需要再次检索它。所以我想我可以做到以下几点:

<ui:composition ...>
  <c:set var="id" value="#{jsfSupport.generateId(id)}" />
  <div class="myComponent" id="#{id}">
     ...
  </div>
  <script type="text/javascript">
    document.getElementById('#{id}');
  </script>
</ui:composition>

但这不起作用。无论如何,id都会重新生成,我得到两个不同的。 有什么想法是理想的方法吗?

【问题讨论】:

  • 我能问您如何从包含/使用上述 ajax 组件的页面访问生成的“id”吗?例如:如果你必须重新渲染自定义的 ajax 组件,你会怎么做?
  • @bchetty 你不能。如果需要重新渲染,需要传入一个Id。自动生成的 ID 仅在与组件没有外部交互的情况下使用。
  • 感谢您的快速响应! :)

标签: java jsf jstl facelets


【解决方案1】:

&lt;c:set&gt; 在 Facelets 中意味着别名,而不是 JSP 中的赋值。因此,每次使用 #{id} 都会转换为对 #{jsfSupport.generateId(id)} 的单独调用,这会导致您描述的问题。

您可以编写自己的&lt;c:set&gt; 标记版本,它只会对传递的表达式求值一次,并保存返回值:

public class SetOnceHandler extends TagHandler
{
    private TagAttribute var;
    private TagAttribute value;

    public SetOnceHandler(TagConfig cfg) 
    {
        super(cfg);
        value = getRequiredAttribute("value");
        var = getRequiredAttribute("var");
    }

    public void apply(FaceletContext ctx, UIComponent parent) 
    {
        ctx.setAttribute(var.getValue(ctx), value.getObject(ctx));
    }
}

【讨论】:

  • 这完美!谢谢。我很惊讶没有开箱即用的东西......
  • 我也面临着完全相同的问题。您能否解释一下为了让这个处理程序就位需要做些什么?
猜你喜欢
  • 1970-01-01
  • 2017-08-25
  • 2011-06-03
  • 2011-01-11
  • 2013-02-04
  • 2021-10-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多