This website uses cookies to ensure you get the best experience. Learn More.
Listing out context variables
While developing a theme I was thinking how can I know all the variables that I can access in my free marker templates? Won't it be great if I can write a utility program which can list out all the variables and objects that can be accessed from our theme or other templates files? Context Contributor concept can be used for this purpose. Actually using Context Contributor we can write a piece of code to inject contextual information which can be reused in various template files. If you are not aware of context contributor please visit my article http://proliferay.com/context-contributor-concept-in-liferay-7dxp/ .
Using the Liferay IDE we can create the project structure.
Our context contributor class has to implements TemplateContextContributor interface and we need to implement the below method.
public void prepare(Map<String, Object> contextObjects, HttpServletRequest request) { //The fun part is here }
If we see the above code, the first parameter contextObjectcts is the map which contains all the contextual information as key-value pairs. We can iterate all the items of the map and write it to a file. Here is the complete code of the method. This method writes a file in my D drive with a file name all-variables.html.Of course, you can change it the way you want.
@Override public void prepare( Map<String, Object> contextObjects, HttpServletRequest request) { PrintWriter writer; try { writer = new PrintWriter("D:\\all-variables.html", "UTF-8"); StringBuffer stb = new StringBuffer(); stb.append("<html>"); stb.append("<body>"); stb.append("<table border=\"1\">"); stb.append("<tr>"); stb.append("<th>Variable Name</th>"); stb.append("<th>Variable Value</th>"); stb.append("</tr>");
for (Map.Entry<String, Object> entry : contextObjects.entrySet()) { stb.append("<tr>"); stb.append("<td>"+entry.getKey()+"</td>"); stb.append("<td>"+entry.getValue()+"</td>"); // System.out.println(entry.getKey() +" = = "+ entry.getValue()); stb.append("</tr>"); } stb.append("</table>"); stb.append("</body>"); stb.append("</html>"); writer.println(stb.toString()); writer.close(); } catch (FileNotFoundException | UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
You just deploy the module and access any pages. This code will be executed and your file is ready. Now you have all the contextual information which can be used the theme development as well as writing ADT.