-
Notifications
You must be signed in to change notification settings - Fork 14
Tutorial 0.4 Parameter Passing
In this tutorial we will go over how to pass a parameter to a view.
Having a static hello world page is nice, but it would be better if we could pass a message to our hello world page to display it. To do this, we first need to change our view to accept a message and display it.
Changing our view to accept a message is easy. Open the index.clj file and change the line which looks like:
(defview []
to
(defview [message]
Since views are basically functions, we can simply add a parameter to the function then use it. To add a parameter to a view function, simply add it to the vector when defining the view.
Now that we have a message parameter, we can display it. Change the line:
[:p "Hello World!"]]))
to
[:p (clj-html.helpers/h message)]]))
We assume message is a string, and simply display it as the content of our view. Since the message may be something the user enters, we use the “h” function in clj-html.helpers which sanitizes the message (mainly strips script tags) to avoid a cross site scripting vulnerability. How to avoid website vulnerabilities is outside the scope of this tutorial. However, if you’re displaying text which may have been entered by a user, it’s generally a good idea to sanitize it with the “h” function.
The last thing we need to do is pass a message to our view to display it. This requires us to update our home controller.
In the home_controller.clj file, change the action:
(defn index [request-map] (render-view (home-request-map request-map)))
to
(defn index [request-map] (render-view (home-request-map request-map) "Hello World! (from controller)"))
If we save both files and reload our page, we should see a message from the controller.