Table of contents
- 1 Creating a ViewComponent support in the NVelocity View Engine
- 2 Using a dictionary to pass parameters
- 3 Using a list of key/value pairs
- 4 Parameters data types
- 5 A small example: security component
ViewComponents with NVelocity
Creating a ViewComponent support in the NVelocity View Engine
NVelocity allows you to create your own directives, so that's how we introduced components to it. Basically you can use:
for inline components
#component(ComponentName)
for components with body content (aka block components)
#blockcomponent(ComponentName) some content #end
ViewComponents have access to the IRailsContext so you can access form parameters, session, etc. Sometimes however it's important to specify some parameters.
Using a dictionary to pass parameters
Use the name of the component followed by a dictionary string. For more information on dictionary expressions see [[MonoRail:NVelocity]]
#component(MyFirstComponent "%{firstParam='some value',anotherParam='other value'}")
You can then access the parameters from the component code:
public class MyFirstComponent: ViewComponent { public override void Render() { object param1 = Context.ComponentParameters["firstParam"]; object param2 = Context.ComponentParameters["anotherParam"]; ... } }
Using a list of key/value pairs
In this case you need to use the keyword with followed by a sequence of key/value pairs:
#component(ComponentName with "name=john" "address=some address")
You're free to use interpolation as well
#component(ComponentName with "name=${customer.name}")
You can gain access to the component parameters using the Context.ComponentParameters too.
Parameters data types
Every data type is supported. However literal values will be automatically converted to text. If you want to specify a different type, create a varible on NVelocity or use some structure data available on the view.
The parameter value below will be converted to string
#component(ComponentName with "age=1")
The parameter value below will remain an Int32
#set($age = 27)
#component(ComponentName with "age=${age}")
A small example: security component
The view snippet:
#blockcomponent(SecurityComponent with "role=admin") this will only be rendered if the current user is in the specified role #end
The component code:
using Castle.MonoRail.Framework; namespace WebApp { public class SecurityComponent : ViewComponent { bool shouldRender; public override void Initialize() { String role = ComponentParameter["role"] as String; shouldRender = RailsContext.User.IsInRole( role ); } public override void Render() { if (shouldRender) Context.RenderBody(); } } }