Hi @vhochsteintef ,
To dynamically include Component B within Component A and pass a custom instance of SlingModelB to it, you can follow these steps:
1. Create Component A’s Sling Model (SlingModelA)
Component A will need a Sling Model to manage the logic of dynamically including Component B.
package com.example.core.models;
import com.example.core.models.SlingModelB;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.Self;
import javax.inject.Inject;
@Model(adaptables = Resource.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class SlingModelA {
@Self
private Resource resource;
@Self
private SlingModelB slingModelB;
public SlingModelB getSlingModelB() {
// Logic to initialize and customize SlingModelB
return slingModelB;
}
}2. Component A HTL (HTML)
In the HTL of Component A, use the data-sly-resource attribute to dynamically include Component B and pass SlingModelB. There are 2 examples how you can reuse sling models.
<!-- componentA.html -->
<div class="component-a">
<!-- Other HTML -->
<!-- How to include component B from A -->
<div data-sly-resource="${'path/to/componentB' @ resourceType='example/components/componentB'}">
</div>
<sly data-sly-use.slingModelA="com.example.core.models.SlingModelA"></sly>
<!-- Example 1 -->
<sly data-sly-use.slingModelB="com.example.core.models.SlingModelB"></sly>
<!-- Example 2 -->
<sly data-sly-set.slingModelBFromA="${slingModelA.slingModelB}"></sly>
<!-- Other HTML -->
</div>3. Component B Sling Model (SlingModelB)
Ensure SlingModelB is structured to accept dynamic data, possibly through constructor injection.
package com.example.core.models;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.injectorspecific.ValueMapValue;
@Model(adaptables = Resource.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class SlingModelB {
@ValueMapValue
private String property1;
// Other properties and logic
public String getProperty1() {
return property1;
}
// Other getters
}4. Component B HTL (HTML)
Render the data passed from Component A inside Component B.
<!-- componentB.html -->
<div class="component-b">
<p>${slingModelB.property1}</p>
<!-- Render other properties of SlingModelB -->
</div>