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

829 views Asked by At

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")
2

There are 2 answers

1
zigazou On BEST ANSWER

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:

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.

0
Jezen Thomas On
import Import
import Text.Blaze.Html       (preEscapedToHtml)
import Text.Shakespeare.Text (stextFile)

myWidget :: Widget
myWidget = toWidget . preEscapedToHtml $ $(stextFile "templates/some-file.html")