Content Fragment - Get value by name and not node

Avatar

Avatar

jsolano918

Avatar

jsolano918

jsolano918

14-01-2021

I'm working on a content fragment which has several single line, multi-line and binary inputs. One example of a single line input, I've named title. In my HTML, I'm able to access the title value like this:

 

Current HTML: ${fragment.elements[0].value}

 

This works, but it's not the best method if I want to change the content fragment order later in any way. Is there a way to access the value of my title input some other way?

 

Example: ${fragment.elements.title.value} or ${fragment.elements["title"].value}

 

So far everything I've tried doesn't work and I can't seem to find any other way of getting this to work.

Accepted Solutions (1)

Accepted Solutions (1)

Avatar

Avatar

BrianKasingli

MVP

Avatar

BrianKasingli

MVP

BrianKasingli
MVP

14-01-2021

@jsolano918 

Writing backend Apache Sling Models with business logic, you should be able to control and return exactly what you need, without any complicated business logic from the view. 

Code Example for Sling Model:

 

 

package com.sourcedcode.aem.core.models;

import com.adobe.cq.dam.cfm.ContentFragment;
import lombok.Getter;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.SlingObject;

import javax.annotation.PostConstruct;
import java.util.Objects;
import java.util.Optional;

@Model(adaptables = Resource.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
@Getter
public class MyModel {

    @SlingObject
    private ResourceResolver resourceResolver;

    private String title;
    private String price;
    private String latitude;
    private String longitude;

    @PostConstruct
    protected void init() {
        ContentFragment cf = Optional.ofNullable(
                resourceResolver.getResource("/content/dam/my-site/cfg/fragment"))
                .map(e -> e.adaptTo(ContentFragment.class)).orElse(null);
        if (cf != null) {
            title = Objects.requireNonNull(
                    cf.getElement("title").getValue().getValue()).toString();
            price = Objects.requireNonNull(
                    cf.getElement("price").getValue().getValue()).toString();
            latitude = Objects.requireNonNull(
                    cf.getElement("latitude").getValue().getValue()).toString();
            longitude = Objects.requireNonNull(
                    cf.getElement("longitude").getValue().getValue()).toString();
        }
    }
}

 

 

Example for Sightly

 

 

<sly data-sly-use.model="com.mysite.models.MyModel"></sly>
${model.title}
${model.price}
${model.latitude}
${model.longitude}

 

 

 

 

 

 

 

Answers (0)