-
Notifications
You must be signed in to change notification settings - Fork 24
How do I dynamically display a view by using an event filter?
To dynamically display a view page, the best choice is to create a filter. In our example, lets call our event-filter DisplayViewByLanguage
. In your Mach-I config file instead of calling <view-page name="page" />
you will need to call the filter and pass it any parameters that you may need. For the sake of our example, we need to conditionally display a view based on the language of the user has requested.
We will use a lang
parameter to display an english or french version of a page. This could be an event argument, a session variable or a combination of both. Your event-handler would be something like this:
<event-handler event="something" access="public">
<filter name="DisplayView">
<parameter name="en" value="page.english" />
<parameter name="fr" value="page.french" />
</filter>
</event-handler>
Now assuming that I have my current active language stored in a session.lang
variable, my filterEvent
method in my DisplayViewByLanguage
would do something like this:
<cffunction name="filterEvent" access="public" returntype="boolean" output="true"
hint="Runs the filter event.">
<cfargument name="event" type="MachII.framework.Event" required="true" />
<cfargument name="eventContext" type="MachII.framework.EventContext" required="true" />
<cfargument name="paramArgs" type="struct" required="true" />
<cfset var viewName = "" />
<cfif session.lang EQ "fr">
<cfset viewName = arguments.paramArgs["fr"] />
<cfelse>
<cfset viewName = arguments.paramArgs["en"] />
</cfif>
<cfset arguments.eventContext.displayView(arguments.event, viewName) />
<cfreturn true />
</cffunction>
Notice that we need to explicity call the displayView
method in the EventContext
to display the page. This is the same way that the <view-page>
command accomplishes displaying a view, however our filter has the ability to pick the required view at runtime based on the language the user has selected to view the website in.
Please note that the output attribute of the cffunction tag is set to true. If you do not set it to true or if you leave this attribute off, the content in the display view will not be displayed.
Our example is not a full featured filter and does not address other implementation problems such as how the language is put into a session variable (a plugin preProcess is good for this), it defaults to the English version of a page by default and does not validate that the developer passes in a view for both English and French. Also, it only accommodates English and French. It would ideal if the different languages it supports could be passed in as configuration time parameters when the event-filter is registered.