Language GET param and cookie; simple i18n example
This commit is contained in:
parent
7275d9ecfc
commit
79b780fec2
@ -25,6 +25,7 @@ module Yesod.Definitions
|
||||
, authCookieName
|
||||
, authDisplayName
|
||||
, encryptedCookies
|
||||
, langKey
|
||||
) where
|
||||
|
||||
import qualified Hack
|
||||
@ -79,3 +80,6 @@ authDisplayName = "DISPLAY_NAME"
|
||||
|
||||
encryptedCookies :: [String]
|
||||
encryptedCookies = [authDisplayName, authCookieName]
|
||||
|
||||
langKey :: String
|
||||
langKey = "_LANG"
|
||||
|
||||
@ -103,9 +103,14 @@ toHackApp'' y tg env = do
|
||||
rr = cs env
|
||||
res <- runHandler handler errorHandler rr y tg types
|
||||
let acceptLang = lookup "Accept-Language" $ Hack.http env
|
||||
-- FIXME get languages from a cookie as well
|
||||
let langs = maybe [] parseHttpAccept acceptLang
|
||||
responseToHackResponse langs res
|
||||
langs' = case lookup langKey $ rawCookies rr of
|
||||
Nothing -> langs
|
||||
Just x -> x : langs
|
||||
langs'' = case lookup langKey $ rawGetParams rr of
|
||||
Nothing -> langs'
|
||||
Just x -> x : langs'
|
||||
responseToHackResponse langs'' res
|
||||
|
||||
httpAccept :: Hack.Env -> [ContentType]
|
||||
httpAccept = map TypeOther . parseHttpAccept . fromMaybe ""
|
||||
|
||||
34
examples/i18n.hs
Normal file
34
examples/i18n.hs
Normal file
@ -0,0 +1,34 @@
|
||||
{-# LANGUAGE QuasiQuotes #-}
|
||||
import Yesod
|
||||
import Yesod.Constants
|
||||
import Hack.Handler.SimpleServer
|
||||
|
||||
data I18N = I18N
|
||||
|
||||
instance Yesod I18N where
|
||||
handlers = [$resources|
|
||||
/:
|
||||
Get: homepage
|
||||
/set/$lang:
|
||||
Get: setLang
|
||||
|]
|
||||
|
||||
homepage = return Hello
|
||||
|
||||
setLang lang = do
|
||||
addCookie 1 langKey lang
|
||||
redirect "/"
|
||||
return ()
|
||||
|
||||
data Hello = Hello
|
||||
|
||||
instance HasReps Hello where
|
||||
reps = [(TypeHtml, const $ return $ Content $ return . cs . content)]
|
||||
where
|
||||
content [] = "Hello"
|
||||
content ("he":_) = "שלום"
|
||||
content ("es":_) = "Hola"
|
||||
content (_:rest) = content rest
|
||||
|
||||
|
||||
main = putStrLn "Running..." >> run 3000 (toHackApp I18N)
|
||||
Loading…
Reference in New Issue
Block a user