Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yesod, howto generate type-safe link from JSON-data in Javascript / Julius

Tags:

haskell

yesod

I've a route

/notes/#NoteId    NoteR    GET

From another page, I want to link to it. When using "classic" hamlet, it's easy:

<a href=@{NoteR $ entityKey note}>notetitle

I want my page to be more dynamic and get JSON-data which contains the note-information plus note-id. How do I generate correct and typesafe-links?

I've already this code in a .julius file, but it fails to compile because it expects a "NoteId". I should insert obj.id somewhere in the URL interpolation @{..}... Any clues how to do that?

function loadnotes() {
var list = $("#results");
jQuery.getJSON("@{NotesR}",
    function(o){
        $.each(o, function (i, obj) {
            $('<a href=@{NoteR}/>' + obj.title + '</a>').appendTo(list);
        })});
}
window.onload = loadnotes;

EDIT:

I have this in Model.hs:

instance ToJSON (Entity Note) where
    toJSON (Entity nid (Note title content created_at updated_at userId)) = object
        [ "id" .= nid
        , "title" .= title
        , "content" .= (unTextarea content)
        , "created_at" .= created_at
        , "updated_at" .= updated_at
        , "userId" .= userId ]
like image 778
davidbe Avatar asked Jan 01 '13 21:01

davidbe


1 Answers

I would recommend having the NotesR route return the fully rendered URL instead of just the note ID.

Edit: I've added a cookbook entry to demonstrate this approach: https://github.com/yesodweb/yesod/wiki/Using-type-safe-urls-from-inside-javascript

like image 163
Michael Snoyman Avatar answered Oct 01 '22 23:10

Michael Snoyman