我在 pageContext 中有一个对象列表,我想要在 select 的选项标签的数据属性中使用它的一些属性。
下面是jsp代码:
<form:select class="required chzn_a" disabled="${view}" path="one.id" id="one">
<form:option value="">Select</form:option>
<form:options items="${objectList}" itemValue="id" itemLabel="name"/>
</form:select>
据我所知 form:options 标签不支持这样的自定义。相反,您可以像这样自己循环选择选项:
<form:select class="required chzn_a" disabled="${view}" path="one.id" id="one">
<form:option value="">Select</form:option>
<c:forEach items="${objectList}" var="objectListEntry">
<form:option value="${objectListEntry.id}" data-code="${objectListEntry.code}">${objectListEntry.name}</form:option>
</c:forEach>
</form:select>
Spring 表单标签实现了 DynamicAttributes 接口,并且 tld 中未显式定义的所有属性都将添加到生成的标签中。
我遇到了同样的问题,如何将属性(ISO 3 字母国家代码)添加到选择的选项中。一本字典和一点 jQuery 效果很好:
var countryDict = {}; // make a dictionary of {country ID : country iso Code}
countryList.forEach(element => {
countryDict[element.id] = element.iso3Code;
});
$('#myCountry > option').each(function(){ // use that dictionary to add ISO code as an attribute to country options.
$(this).attr('isoCode', countryDict[$(this).val()]);
});
使用更改 tld 文件覆盖 spring 选项标签 创建新参数标签并在 tld 中定义 类似这个
public class OptionsTagNew extends OptionsTag {
@Getter
List<OptionalAttributeOptionModel> optAttr = new ArrayList<>();
@Override
protected void writeOptionalAttributes(TagWriter tagWriter) throws JspException {
super.writeOptionalAttributes(tagWriter);
for (OptionalAttributeOptionModel x : optAttr) {
writeOptionalAttribute(tagWriter, x.getName(), x.getValue());
}
}
public void setOptAttr(OptionalAttributeOptionModel optAttr) {
this.optAttr.add(optAttr);
}
}
@Getter
@Setter
@AllArgsConstructor
class OptionalAttributeOptionModel {
private String name;
private String value;
}
@Getter
@Setter
public final class AddOptionAttributeTag extends TagSupport {
private String name;
private String path;
@Override
public int doStartTag() throws JspException {
OptionsTagNew parent = (OptionsTagNew) findAncestorWithClass(this, OptionsTagNew.class);
if (parent == null) {
throw new JspException("AddOptionAttributeTag must be within a OptionTag!");
}
parent.setOptAttr(new OptionalAttributeOptionModel(name, getPathValue(parent.getItems())));
return SKIP_BODY;
}
private String getPathValue(Object items) {
BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(items);
return Objects.requireNonNull(wrapper.getPropertyValue(this.path)).toString();
}
@Override
public int doEndTag() throws JspException {
return super.doEndTag();
}
@Override
public void release() {
this.name = null;
this.path = null;
super.release();
}
}