Context: I am running Magnolia CMS 5.x & try to programmatically (in freemarker
) check if a node exist to avoid getting an exception thrown when trying to access it via ${damfn.getAssetLink(<someUUID>)}
or similar.
Is there a way to check if a Node with a given UUID exist?
I found nothing interesting when looking at NodeUtil.java, SessionUtil.java, Session.java, JCRUtils, TemplatingFunction (cmsfn:
) & DamTemplatingFunctions (damfn:
)
I only could find that you can check via path using jackrabbit.510166.n4.nabble.com/Checking-if-node-exists-td516003.html
TemplatingFunction.java
(cmsfn:
) explained by Magnolia CMS' teamDamTemplatingFunctions.java
(damfn:
) explained by Magnolia CMS' teamDamTemplatingFunctions.java
code(See my update below for a simple solution using standard Magnolia directives)
How about using the search searchfn
https://documentation.magnolia-cms.com/display/DOCS/searchfn
or QueryUtil
and searching by UUID:
https://wiki.magnolia-cms.com/display/WIKI/JCR+Query+Cheat+Sheet
SELECT * FROM [nt:base] WHERE [jcr:uuid] = '7fd401be-cada-4634-93fa-88069f46297b'
Using it in Freemarker:
You can wrap every Java function, such as search, in a custom freemarker directive.
See documentation.magnolia-cms.com/display/DOCS/Templating+functions
In your module xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module SYSTEM "module.dtd" >
<module>
...
<components>
<id>main</id>
<component>
<type>com.company.my.MyTemplatingFunctions</type>
<implementation>com.company.my.MyTemplatingFunctions</implementation>
<scope>singleton</scope>
</component>
</components>
...
com.company.my.MyTemplatingFunctions.doesNodeExist()
calls the QueryUtil
standard class - or SessionUtil
such as:
package com.company.my;
public class MyTemplatingFunctions {
public boolean doesNodeExist(String workspace, String id){
if ( SessionUtil.getNodeByIdentifier(workspace, id) != null ){
return true;
}
return false;
}
}
Then in your .ftl
:
[#-- @ftlvariable name="myfn" type="com.company.my.MyTemplatingFunctions" --]
${myfn.doesNodeExist(relevantWorkspace, someUUID)}
== Update ==
Just checking the Magnolia docs:
https://documentation.magnolia-cms.com/display/DOCS/damfn#damfn-Getasset
Does this not work?
[#assign myAsset = damfn.getAsset("jcr:20d6e4e3-fe53-4b23-8d64-6e67a1c1667f")!]
where you can then check with if
/ else
in Freemarker for myAsset
?
This would look like the simplest solution. Haven't tested it but it looks as if it should be possible to pass the UUID together with the jcr:
prefix.
Furthermore: if you don't need to explicitly check if the asset exists, but just don't want to get a template error in the log, you can add a !
like this:
${damfn.getAssetLink(<someUUID>)!}
then you don't get a template error, just a WARN message in the log.