Oracle APEX Template Directives - Directing More Than Just Templates
This is a quick blog post to show an easy way to use Template Directives in Oracle APEX as an alternative to common implementations of a specific problem. What problem is that? I have a report with a column that has a small set of distinct values, such as a "STATUS" column with 'Active' or 'Inactive' as its possible values. I want to display these as icons instead of text.
I have seen this as the solution over and over again which works but may not be ideal.
SELECT '<span class="fa ' || CASE STATUS
WHEN 'Active' THEN
'fa-check'
ELSE
'fa-remove'
END || '" aria-hidden="true"></span>' AS STATUS
......
The column attribute "Escape special characters" is turned off and the icon is displayed. Job done, right?
Well, this approach has its drawbacks. The most important is the risk of malicious code injection when you disable this attribute. Another issue is that users can no longer filter by the original values in the "STATUS" column, such as 'Active' or 'Inactive'. Instead, they have to select the generated HTML, which might not be clear to them.
To avoid both of these issues we can use Template Directives in the attributes for the report's STATUS column under the Column Formatting section -> HTML Expression.
<span class="fa{case STATUS/}
{when Active/}
fa-check
{otherwise/}
fa-remove
{endcase/}" aria-hidden="true"></span>
This results in the same span tag being generated, but now we use the CASE template directive to test the STATUS column value and display the relevant icon. This approach preserves the escaping of any embedded special characters and also keeps the original values for filtering.
I hope you found this useful and start using this powerful yet simple feature within Oracle APEX if you aren't already. For more information on template directives, please refer to the official Oracle documentation.