Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In


    Refactor an Elm View with Variables for Re-use and Readability

    Enrico BuonannoEnrico Buonanno

    Views in Elm do not involve any markup or special syntax, but are just regular Elm code. As a result, you can refactor your views, reuse variables, and so on - just as with any other code. This means that it's easy to ensure that the code for your views is readable and maintainable.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson


    Instructor: 00:03 Here you can see, on the left side, the Elm code that generates our view, a preview in the middle, and, on the right side, the actual HTML that is generated.

    00:12 You can see that there's a very simple, one-to-one correspondence. For our form element here in the Elm, we have an outer form element in the HTML and that wraps, a list of divs, and you can find the corresponding divs in the HTML.

    00:29 When you look at the Elm code, this might seem just a slightly different syntax to write the same thing. The important thing to keep in mind though is that the Elm representation of a view is just normal Elm code. There's nothing special about this div. This is simply a function. This means that you can use variables and refactor things.

    00:49 Let's have a look at that. For example, you could say that this form has a header, a body, and a footer and you might like to express this. For example, let's say that this div with the H1, that acts as a header. You could put this into a variable that you call header. Let's say let header, this div that we've just defined.

    01:21 Then you could say that the body of the form is this set of fields. Let's just create a new div that wraps those. Here I could put these two divs. Finally, the footer is this div here that contains the buttons. You could say that the result is a form made of its header, its body, and its footer.

    02:00 Now if we compile this and you see that it looks exactly the same, but somehow, we're giving more meaning to these visual elements. You could also decide that this function is a bit too long for your liking, so you could extract these variables into top-level functions. I can put them down here and put them at top level. Then your main simply returns a form like this.

    02:34 You can see how you can really write very readable and maintainable code for views.