Получение значений из многополюсного компонента в HTL в AEM 6.5 - PullRequest
1 голос
/ 15 января 2020

У меня есть компонент мультиполя, следующий за этим форматом

<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0" xmlns:nt="http://www.jcp.org/jcr/nt/1.0"
    jcr:primaryType="nt:unstructured"
    jcr:title="Awards List"
    sling:resourceType="cq/gui/components/authoring/dialog">
    <content
        jcr:primaryType="nt:unstructured"
        sling:resourceType="granite/ui/components/coral/foundation/container">
        <layout
            jcr:primaryType="nt:unstructured"
            sling:resourceType="granite/ui/components/coral/foundation/tabs"
            type="-nav"/>
        <items jcr:primaryType="nt:unstructured">
            <awards
                jcr:primaryType="nt:unstructured"
                jcr:title="Awards Properties"
                sling:resourceType="granite/ui/components/foundation/section">
                <layout
                    jcr:primaryType="nt:unstructured"
                    sling:resourceType="granite/ui/components/coral/foundation/fixedcolumns"/>
                <items jcr:primaryType="nt:unstructured">
                    <column
                        jcr:primaryType="nt:unstructured"
                        sling:resourceType="granite/ui/components/coral/foundation/container">
                        <items jcr:primaryType="nt:unstructured">
                            <description
                                jcr:primaryType="nt:unstructured"
                                sling:resourceType="granite/ui/components/coral/foundation/form/textarea"
                                fieldLabel="Description"
                                name="./description"/>
                            <awards
                                jcr:primaryType="nt:unstructured"
                                sling:resourceType="granite/ui/components/coral/foundation/form/multifield"
                                composite="{Boolean}true"
                                fieldLabel="Awards">
                                <field
                                    jcr:primaryType="nt:unstructured"
                                    sling:resourceType="granite/ui/components/coral/foundation/container"
                                    name="./awards">
                                    <items jcr:primaryType="nt:unstructured">
                                        <column
                                            jcr:primaryType="nt:unstructured"
                                            sling:resourceType="granite/ui/components/coral/foundation/container">
                                            <items jcr:primaryType="nt:unstructured">
                                                <awardtype
                                                    jcr:primaryType="nt:unstructured"
                                                    sling:resourceType="granite/ui/components/coral/foundation/form/select"
                                                    fieldDescription="Select Award Type"
                                                    fieldLabel="Award Type"
                                                    name="./type">
                                                    <items jcr:primaryType="nt:unstructured">
                                                        <gold
                                                            jcr:primaryType="nt:unstructured"
                                                            text="gold"
                                                            value="gold"/>
                                                        <silver
                                                            jcr:primaryType="nt:unstructured"
                                                            text="silver"
                                                            value="silver"/>
                                                        <bronze
                                                            jcr:primaryType="nt:unstructured"
                                                            text="bronze"
                                                            value="bronze"/>
                                                        <other
                                                            jcr:primaryType="nt:unstructured"
                                                            text="other"
                                                            value="other"/>
                                                    </items>
                                                </awardtype>
                                                <award
                                                    jcr:primaryType="nt:unstructured"
                                                    sling:resourceType="granite/ui/components/coral/foundation/form/textfield"
                                                    fieldDescription="Name of Award"
                                                    fieldLabel="Award Name"
                                                    name="./award"/>
                                            </items>
                                        </column>
                                    </items>
                                </field>
                            </awards>
                        </items>
                    </column>
                </items>
            </awards>
        </items>
    </content>
</jcr:root>

И я пытаюсь просто вывести содержимое мультиполя в список. И я пытаюсь сделать это с

<ul data-sly-list="${properties.awards}">
    <li>${item.type}</li>
</ul>

Но это ничего не делает. В качестве теста я сделал

<ul data-sly-list="${[1,2,3,4]}">
    <li>${item}</li>
</ul>

, который работал. Посмотрев в Интернете, я нашел такие ресурсы, как https://helpx.adobe.com/experience-manager/using/aem65_coral_resourcetypes.html#UseaDataSourceObjecttopopulateaSelectfield

Но, похоже, они используют классы Java для создания мультиполя, и я надеюсь, что в этом нет необходимости. Мне не нужны никакие дополнительные логи c, все, что я пытаюсь сделать, это отобразить значения полей.

Есть ли что-то, что я делаю не так? Требуется ли использование мультиполей для создания класса Java?

РЕДАКТИРОВАТЬ: я пытался получить содержимое с помощью объекта javascript, имея файл js с содержимым

"use strict";

use(function () {
    var description = granite.resource.properties["description"];
    var awards = granite.resource.properties["awards"];

    return {
        description: description,
    };
});

и используя

<div data-sly-use.awardsObject="awardslist.js">
    <p>
        ${awardsObject.description}
        ${awardsObject.awards}
    </p>
</div>

Но я не могу получить награды, чтобы что-то вернуть. Я попытался структурировать объект awards, чтобы посмотреть, получу ли я какие-либо данные, но не получил ни одного.

1 Ответ

3 голосов
/ 15 января 2020

Вероятно, это связано с тем, что вы используете составное мультиполе (посмотрите на свойство composite="{Boolean}true" против мультиполя), которое обычно обрабатывает содержимое формы как составное и создает дочерние узлы под текущим компонентом для хранения значений свойства.

Цитирование из документов

true для обработки значения содержимого формы как составного.

Составное многоуровневое поле поддерживает вложение другого многоуровневого объекта (составного или нет). Тем не менее, некомпонентный не поддерживает вложенность.

Например, если задано свойство name для поля address, а поля-потомки имеют следующие значения свойства name:

street1
street2  
postcode 
city/name 
city/state  
city/country/name
gps/lat 
gps/long

это сохранит следующую структуру в хранилище:

 + addresses   + item0
     - street1
     - street2
     - postcode
     + city
       - name
       - state
       + country
         - name
     + gps
       - lat
       - long   + item1
     - street1
     - street2
     - postcode
     + city
       - name
       - state
       + country
         - name
     + gps
       - lat
       - long

Поскольку объект properties содержит только свойства текущего ресурса, ${properties.awards} будет нулевым и, следовательно, он ничего не отображает.

Было бы проще создать либо модель слинга, либо Java / Javascript Использовать класс API, чтобы получить список, а затем использовать его в файле HTL.

Пример JS Использование API

"use strict";

use(function () {
    var awards = resource.getChild("awards").listChildren();

    return {
        awards: awards,
    };
});

Пример кода HTL

<sly data-sly-use.children="children.js">
    <ul data-sly-list.award="${children.awards}">
        <li>${award.type}</li>
    </ul>
<sly>

Обратите внимание, что объект properties, который является экземпляром ValueMap возвращает только свойства текущего ресурса. Поскольку значения мультиполя хранятся как дочерние ресурсы, вам необходимо получить доступ к дочернему ресурсу, прежде чем обращаться к его свойствам.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...