I am calling ComponentPresentationFactory.getComponentPresentation(componentURI, templateURI) method to retrieve a dynamic component in my Page Controller. The Component Presentation object returned by this method has the ComponentImpl, ComponentTemplateImpl and other fields set on it, but not the ViewModel.
I used the following TBB's in my dynamic component template in Tridion
- Generate dynamic component presentation
- Add inherited metadata to component
- Publish binaries for component
My view model class extends TridionViewModelbase and has the annotation
@ViewModel (
rootElementNames = {"article"},
setComponentObject = true)
where "article" is the Root Element Name of the component schema.
When I use the component as embedded on the page (with non-dynamic template), I get the ViewModel on the Component Presentation object (In this case my Page Controller calls pageFactory.findPageByUrl method).
Now for my view I use Thymeleaf and so I am not using any jsp tags. I am on dd4t2.0.2
What am I missing here for retrieving dynamic component? Am I calling the correct API? Is there any example for dynamic component in java?
Update after comment
I retrieve the view models from the component presentation in my controller and create a list of them which I then set on the request (Spring frameworks view model). In my Thymeleaf view I iterate over the list and display the fragment related to the view models name. So in the controller I have something like…
Page pageModel = pageFactory.findPageByUrl(url, publicationResolver.getPublicationId());
List<ComponentPresentationModel> cpModelList = new ArrayList<ComponentPresentationModel>();
for (ComponentPresentation cp : pageModel.getComponentPresentations())
{
if (!CollectionUtils.isEmpty(cp.getAllViewModels()))
{
for (String key : cp.getAllViewModels().keySet())
{
BaseViewModel viewModel = cp.getViewModel(key);
String name = String.format("%s-%s", RenderUtils.fixUrl(RenderUtils.getViewName(cp)), key);
ComponentPresentationModel cpModel = new ComponentPresentationModel(name, viewModel);
cpModelList.add(cpModel);
}
}
}
In Thymeleaf view …
<div th:each="cp,cpIndex : ${componentPresentationModel}">
<th:block th:switch="${cp.name}">
<th:block th:case="'generic-content-Content'">
<div th:replace="components/generic-content :: Content(component=${cp.model})"></div>
</th:block>
<th:block th:case="'article-component-template-Article'">
<div th:replace="components/article-component-template :: Article(component=${cp.model})"></div>
</th:block>
</th:block>
</div>