How I link to my fubuMVC actions

I’m in the process of migrating an existing production web project to use fubuMVC and all the power that it provides and I’m currently writing a series on my experiences with it – this is the third in that series.

I’ve already begun to migrate my static content pages and now need to link to them in my spark views.
Obviously hard coding the urls defeats the whole point of routes and actions being malleable so I want a way to look back at  my actions and have fubuMVC find the appropriate url.

This is provided by fubuMVC in the form of Url Resolution and my spark views are already integrated with an overloaded LinkTo() method that allows me to refer back to my actions or input models.

So here’s the first stab at the navigation in my site using this method:

    <div id="menu">
      <ul id="headerLinks">
        <li>${this.LinkTo<HomeController>(c => c.FrontPage()).Text("home")}</li>
        <li>${this.LinkTo<NewsController>(c => c.Root()).Text("news")}</li>
        <li>${this.LinkTo<AboutController>(c => c.Root()).Text("about")}</li>
        <li>${this.LinkTo<LoginController>(c => c.Root()).Text("login")}</li>
      </ul>
    </div>

This works a treat, but I'm not so sure about breaking out into code all the time. Is there anyway I can embrace the tag nature of the spark view engine and have an element that would do this for me?

Spark bindings allow you to do just that - you can add custom elements that wrap your code by simply providing a bindings.xml file in your shared folder allowing you to hook them into the spark view engine.
Here's my bindings.xml file:

<?xml version="1.0"?>
<bindings>
  <element name="linkTo">this.LinkTo&lt;@action&gt;(c => c.@method).Text("child::*")</element>
</bindings>

I’m declaring a new “linkTo” element and chopping up the previous code with parameters I expect on that element.
This allows me to now have a better flowing syntax for my links:

    <div id="menu">
      <ul id="headerLinks">
        <li><linkTo action="HomeController" method="FrontPage()">home</linkTo></li>
        <li><linkTo action="NewsController" method="Root()">news</linkTo></li>
        <li><linkTo action="AboutController" method="Root()">about</linkTo></li>
        <li><linkTo action="LoginController" method="Root()">login</linkTo></li>
      </ul>
    </div>



0 comments: