5
Dog
    name Text
    race Text

getAllDogsR :: Handler Html
getAllDogsR = do
    Dogs<- runDB $ selectList [] [Asc DogName]
    defaultLayout
        [whamlet|
            <ul>
                $forall Entity dogid dog <- Dogs
                    <li>
                        #{show $ unKey (dogid)}
       |]

When I run this code I will get a list of all dog keys that are in my database
like this:

  • PersistInt64 1
  • PersistInt64 2
  • PersistInt64 3
  • PersistInt64 4
  • etc

but what I actually want is to show the pure value of the key
like this:

  • 1
  • 2
  • 3
  • 4
  • etc

My question is how can I achieve this.

BARJ
  • 1,543
  • 3
  • 20
  • 28
  • Does `#{case dogid of PersistInt64 x -> show $ unKey x}` work? – Ry- Nov 08 '13 at 14:56
  • does not work unfortunately – BARJ Nov 08 '13 at 16:19
  • 1
    The function you want is [fromPersistValueText](http://hackage.haskell.org/package/persistent-1.2.3.0/docs/Database-Persist-Types.html#v:fromPersistValueText). However you can also have `module Model.Id` for anchors, ids and things like that. The module will contain class for id rendering: `class PersistId a where persistId :: Key a -> Text` and a couple of instances: `instance PersistId Dog where persistId = either T.pack id . fromPersistValueText . unKey` will do that you want. I think this will be convenient enough. – Samvel Truzyan Nov 09 '13 at 04:40
  • Although you have asked how to print out the IDs as plain text, I suspect you are actually just going to print out the IDs to the user. If you eventually want to use those IDs in a URL, you can do so without any conversion: ` #{dogName dog} ` – Ecognium Nov 09 '13 at 18:17

2 Answers2

2

You need to extract the key out of a KeyBackend first, like so:

extractKey :: KeyBackend backend entity -> String
extractKey = extractKey' . unKey
  where extractKey' (PersistInt64 k) = show k
        extractKey' _ = ""

You should now be able to do

#{extractKey dogid}
Sammy S.
  • 1,280
  • 1
  • 16
  • 31
2

Change

#{show $ unKey (dogid)}

to

#{toPathPiece dogid}
user316146
  • 1,307
  • 1
  • 12
  • 19
  • It would help if you could provide a more detailed answer with a working example, and possibly some contextual explanation. A one line comment is more suited as just that - a comment on the question. – Alex Osborn Apr 07 '14 at 00:22
  • @AlexOsborn: It isn't just a comment, though. It's an answer. It does exactly what he's asking for. – user316146 Apr 07 '14 at 01:18
  • `toPathPiece` is defined in the `path-pieces` package (http://hackage.haskell.org/package/path-pieces), in the `Web.PathPieces` module. If you have a `(Key x)` you can use `toPathPiece x`. – stusmith Apr 29 '14 at 19:57