Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In yesod (haskell), how do I load a plain html-formatted file (not a hamlet) as a widget?

How do I load a plain html-formatted file (not a hamlet-formatted file) as a widget? In other words I'm looking for the html equivalent of:

toWidget $(whamletFile "test.hamlet")
like image 473
daj Avatar asked May 26 '15 04:05

daj


1 Answers

For this you use sendFile in your handler function (see its definition)

The first argument is the Mime Type while the second is the file path.

For example, you could code something like:

getMyFileR :: Handler ()
getMyFileR = sendFile "text/html" "myfile.html"

Here’s Another example. Say I have the following model:

Resource
    filename    FilePath
    mimetype    ContentType

    deriving    Typeable

The handler might look like:

resourceDirectory :: FilePath
resourceDirectory = "resource"

getResourceGetR :: ResourceId -> Handler ()
getResourceGetR resourceId = do
    resource <- runDB $ get404 resourceId

    sendFile (resourceMimetype resource)
             (resourceDirectory </> unpack (resourceFilename resource))

Edit 2015-06-05

sendFile operates at a low level while addScript or $(widgetFile …) operates at a higher level.

$(widgetFile …) uses TemplateHaskell to convert your Hamlet/Cassius/Lucius/Julius templates into actual Haskell source code before your project is compiled. The same applies similarly to [hamlet|…|].

addScriptworks with a Route while sendFile works with a FilePath. This means addScript will be able to detect missing files at compile time. sendFile will detect missing files at runtime.

There are some tools to convert Html to Hamlet:

  • a one line script (which works well for simple Html),
  • html2hamlet.

An equivalent of addScript for Html files does not make sense: addScript will generate a script tag to tell the browser to download an external resource. This does not apply to an Html file.

like image 127
zigazou Avatar answered Sep 27 '22 23:09

zigazou