Menu
  • HOME
  • TAGS

Indented queries in Yesod

haskell,yesod,persistent

I'm not sure what have you already tried, but since this is practically a join (and persistent's type-safe API doesn't support them), running a custom SQL query should be the most efficient solution. If your model looks something like this EntityA key Text value Text deriving Show EntityB foreignKey EntityAId...

compile-time vs. run-time cost of Hamlet templates

haskell,yesod,hamlet

It's been a while since I worked on the code, so don't take this as authoratative (like Daniel mentioned, -ddump-simpl is a good call here). But I don't believe we're using the blaze-html combinators, just the data type. Hamlet itself concatenates strings as much as possible at compile time to...

Send 301 redirect in Yesod

haskell,yesod

You can find an example in the test/YesodCoreTest/Redirect.hs file available in the current Yesod 1.4.9.1 archive: import qualified Network.HTTP.Types as H myR :: Handler Html myR = redirectWith H.status301 HomeR For a list of available response codes, see the Network.HTTP.Types documentation....

Which form to run?

haskell,yesod

So, I'd probably advise moving your counter ID into the URL, so you're doing something like POSTing to /counters/1/increment or something. Feels slightly off to have the ID in a hidden field. However, if you did want to keep it in a hidden field, you can have the form take...

Yesod, getting name-value map, containing HTML form values

haskell,yesod

You can use runRequestBody to get direct access to all of the POST parameters and files.

Cabal build failure on ReadArgs when deploying to OpenShift

haskell,openshift,cabal,yesod

It turns out this was a bug in the cartridge and is fixed now.

How can I store request-local information in Yesod middleware and retrieve it from a Handler?

yesod,middleware

You can use cached and cachedBy for per-request caching.

What does the `import Some.Module as Import` in Yesod mean?

haskell,yesod

In the Haskell language report exporting a module is described as: The form “module M” names the set of all entities that are in scope with both an unqualified name “e” and a qualified name “M.e”. This set may be empty. §5.2 Export Lists An export list identifies the entities...

Using JS-variable in Yesod handler's code

javascript,yesod,julius

No, there's no way to do that. The yesod code runs server side, and the JavaScript client side. The only way to achieve that kind if thing is to have the JavaScript send values back to the server.

Post and Get a variable using yesod server

haskell,yesod

Using global constants is trivial in Haskell: you just write foo = bla somewhere (preferrably with a signature foo :: FooType). foo can then be used anywhere in your module (or even outside, if you export it). Global variables OTOH aren't really possible in Haskell, as such. For the most...

SVG tags in hamlet shakespearean (yesod/haskell) templates?

haskell,yesod,hamlet

You can just include it like any other tags. Don't put spaces before and after equals sign. <svg height="50" width="500">...

Automatically declaration yesod handlers using Template Haskell

haskell,yesod,template-haskell

EDIT: Simple type signature parameterization example added I think there is a problem with function name binding in your mkDeleteHandler. I would try something like this for example (example simplified): mkHandler :: String -> String -> Q [Dec] mkHandler typeName funcName = do funDecl <- [d| funcName :: String ->...

Is there a way to pass a Hamlet block as an argument to a function?

haskell,yesod,hamlet

No, such syntax does not exist.

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

haskell,yesod,shakespeare-text

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...

How can I run Yesod's DB actions in the REPL?

haskell,yesod,persistent

If you're using the Yesod scaffolding, the handler and db functions are provided to let you run handler actions and database queries, respectively, from the repl: $ cabal repl db $ selectList [UserName ==. "foo"] [] Edit: I've also updated Yesod's wiki page on GHCi with this information. It includes...

Coercing types in Persistent

haskell,yesod

As you probably already know, one of Haskell's strengths is strong typing. The persistent-sqlite package takes this to an extreme (which, in my opinion, is a good thing) by requiring that table entries have their own data type. For instance, if you have a table which holds fruits that looks...

Reading the run mode in Yesod

testing,yesod

In the newest versions of the scaffolding, we no longer have the concept of environments. Command line arguments can be used to switch which config files we read from, but that's it. If you'd like access to that information, you could use getArgs.

How to Read Contents of an Uploaded File

haskell,yesod,conduit

This is what I do: postSomethingR = do ((res, _), _) <- runFormPost form case res of FormSuccess (account, file) -> do bytes <- runResourceT $ fileSource file $$ sinkLbs -- Parse the ByteString in another thread parseHandler <- handlerToIO liftIO $ forkIO $ parseHandler $ do case CSV.parseCSV csvSettings...

Composite Primary Key in Yesod

haskell,yesod,template-haskell

I haven't actually used the composite primary key feature myself, but this error makes sense to me. There's not obvious serialization to Text for arbitrary composite keys, and so persistent doesn't generate it for you. If you'd like to use a MovieId inside your URLs, you'll need to manually define...

Different web server on one domain

wordpress,yesod,subdirectory

You can use (a) and (b) behind a proxy (c) -- NGINX is my personal preferred server for that purpose because it is insanely fast and good on resources. http://nginx.org/en/docs/beginners_guide.html#proxy You'd do something like this: server { location / { proxy_pass http://localhost:{port for a}/; } location /wp { proxy_pass http://localhost:{port...

use runDB in a SubSite Yesod

haskell,persistence,yesod

You need to add the following constraint to the postDemoNewR declaration: YesodPersist master => YesodPersistBackend master ~ SqlBackend => … The first constraint tells master must have persistent abilities while the second constraint tells the backend used for persistent should be an SQL backend. You can find something similar in...

Error when starting Yesod app on openshift - command line args?

openshift,yesod

I'm assuming based on the question that you're using the standard scaffolding. If you look in the code, you'll find that uses loadAppSettingsArgs, which is described as: Same as loadAppSettings, but get the list of runtime config files from the command line arguments. If you don't want to pay attention...

Yesod and dynamic Bootstrap/jQuery form

jquery,forms,yesod

The function you're looking for is runRequestBody: http://www.stackage.org/haddock/lts-2.7/yesod-core-1.4.9.1/Yesod-Core-Handler.html#v:runRequestBody

Put static files on “/” in Yesod

haskell,yesod,static-files

ms's comment is correct: you should put FooR before StaticR. In addition, you'll need to turn off overlap checking. The easiest way is probably to use parseRoutesFileNoCheck instead of parseRoutesFile (or parseRoutesNoCheck instead of parseRoutes if you're using the quasiquoter).

How can I create a foreign key constraint using Yesod/Persistent?

postgresql,migration,yesod,persistent

Persistent does not currently have any built-in support for triggers, though it's something we've been wanting to add (simply lacking manpower). For now, you'll have to add the trigger manually.

Where to store API keys and other 'secrets' in a yesod app

haskell,yesod,api-key

There are many approaches to this, mostly depending on what flavor of devops/hosting your prefer. One option is to put a dummy value in the config file and override it with an environment variable at runtime (see: https://github.com/yesodweb/yesod/wiki/Configuration#overriding-configuration-values-with-environment-variables). You can also having an extra settings file for production that overrides...

Kind mismatch in YesodPersist instance declaration

haskell,yesod,persist

It looks like you originally wrote the code using Persistent 2, and are now using Persistent 1.3. On 1.3, you'd need something like type YesodPersistBackend App = SqlPersistT.

Is there a reference for the syntax of the persistent quasiquoter?

haskell,yesod,persistent

There's a Wiki page covering the syntax. The Gt and Desc is an old syntax that's no longer needed, I'll remove the references from the chapter (I thought I'd caught them all already).

Type mismatch using Yesod and Persistent

haskell,yesod,persistent

You need to use runDB around your persistent call.

In Yesod/Haskell, how do I use data from IO with the variable interpolation functionality?

haskell,io,monads,yesod

When working with monad transformers, to convert from some monad m to a transformer t m, you have to use the lift function: lift :: (MonadTrans t, Monad m) => m a -> t m a This is actually the defining method of the MonadTrans typeclass, so the implementation is...

Yesod Mform and hamlet

yesod,hamlet,yesod-forms

I got it. I was not clear of what "tableMform extra" has to return. I know that it has to return something of type [(FormResult a, xml)][1] . But then I was not sure what the type of "forM lis ((w,h) -> mopt intField (fromString w) (Just h) )" --...

why is the cabal sandbox inited after installing yesod-bin?

cabal,yesod

Because it generally confuses people when they can't run yesod directly; installing the executables into ~/.cabal/bin means that the user can always access them. It does leak some information outside of the sandbox, but it's typically the right trade-off to take.

haskell - How to check one default radio in a radioFieldList in yesod

haskell,yesod,yesod-forms

I presume you're using something like areq (radioField ...) "Some Name" Nothing right now. That Nothing value means "no default." To provide a default, replace it with (Just someDefault).

Yesod Form syntax

forms,haskell,yesod

What does the syntax <$> and <*> mean respectively? pure and <*> are two class methods of type class Applicative, <$> is an infix synonym for fmap, which is one of the class methods of Functor. Chatper 11 Functors, Applicative Functors and Monoids of Learn You a Haskell has...

Haskell Yesod: How to read text from file and apply variable interpolation to its content?

haskell,markdown,interpolation,yesod

Well, finally I've found really simple solution. Any quasi quoter could be easily switched to file input rather than inline text with quoteFile function from Language.Haskell.TH.Quote module1. Let's describe in Foundation module following function: import Language.Haskell.TH.Quote (QuasiQuoter, quoteFile) import Text.Shakespeare.Text (st) stFile :: QuasiQuoter stFile = quoteFile st Now we...

Hosting a static site with Yesod

haskell,yesod

Have a look in your browser console, most likely you're getting 404s due to bad relative links. I'd try using a redirect call to point to the static for so that all of the relative links are correct.

Missing imports from Hamlet libraries

haskell,yesod,template-haskell,hamlet

Import Yesod.Core and Yesod.Core.Widget, they will provide the appropriate functions. Also note that they have a online version of the book. And generally if you see import errors, do a search on Hoogle and in most of the cases you are likely to find a solution there....

Yesod's shakespearean templates (hamlet) and IO

haskell,yesod,hamlet,io-monad

Hamlet is just providing an alternate syntax for normal Haskell code, so like normal Haskell, you have to keep your impure actions separate. In other words, you need to run the IO action outside of the template.

fromPathPiece has type ()

haskell,yesod

Take a look at the types for insert and replace (ignoring the constraints for brevity): insert :: val -> m (Key val) replace :: Key val -> val -> m () Branches of a case expression have to have the same type. (Otherwise sck's type would be different depending on...

Lift a value from a Monad - Yesod

haskell,yesod

Since you are running monad actions at the end of your case, you don't need to return the case. isAdmin = do mu <- maybeAuthId case mu of Just "Foo" -> Authorized Just _ -> Unauthorized "You are NOT a Admin !" Nothing -> do setMessage "You have to Login...

Is it possible to order a query by primary key?

haskell,yesod,persistent

I' wasn't sure about the SelectOpts only being applicable to entity value, so I checked that in a small snippet of code. Assuming an entity looks like this: EntityA key Text time UTCTime deriving Show you can just list SelectOpts you're interested in and get the desirable output. The sample...

How to include a comment in an inline yesod javascript template

templates,comments,yesod,shakespeare-text,julius

If you're asking specifically about Julius templates, the answer is that there isn't any built-in commenting syntax, and therefore the only option is JavaScript style comments. However, as you've mentioned, this can conflict with the CPP language extension. One option to work around this is to put the template in...

Couldn't match type Data.Enumerator.Internal.Iteratee with IO

haskell,yesod

Probably you are trying to run old code that does not work with current Yesod. You can get this to compile and run (ghc-7.10.1, yesod-1.4.1.5) with import Data.Enumerator (run_) ... bss <- run_ consume but I'm not sure what you want it to do. As is, it will return an...

Resulting Ambiguous Type Variable in Persistent's `get` call

haskell,monads,yesod,persistent

I think you need to replace: let contacts = map (\(Entity key val) -> (get $ ((contactContact val) :: UserId) )) contacts' with: contacts <- mapM (\(Entity key val) -> (get $ ((contactContact val) :: UserId) )) contacts' (Yes, the Persistent error messages here are terrible, we're working on that...

Yesod 1.2 CSRF protection

haskell,csrf,yesod

The token is stored in the user session. You can get access to it via: fmap reqToken getRequest ...

types mismatch on runSqlite and newTVar

yesod

You need to add liftIO in front of atomically, to lift the IO action into the Persistent monad.

How would I make a generic sort option SelectOpt for all columns?

haskell,yesod,persistent

Try giving sortOrder' a type signature. where sortOrder' :: EntityField Model typ -> SelectOpt Model sortOrder' = case sortOrder of "Asc" -> Asc "Desc" -> Desc This compiles using GHC 7.6.2....

How can I get a type safe route to a static dir (not a static file)?

haskell,yesod

In order to do that, you'll need to use the StaticRoute constructor directly. The identifier generation only generates identifiers for files, not directories, since that's normally what people want (as @zudov explains). You should be able to do something like: @{StaticR $ StaticRoute ["images"] []} ...

Yeson.json.object is applied to too many arguments

haskell,yesod,classy-prelude

object is not in scope in prelude. Which package/module defines this? Yesod.Json Why doesn't it take the key-value pair in the above case? It takes the key value pair just fine. The error message is telling you that object gives you a Value, but you declared getHome to be...

Yesod catchall route

haskell,routes,yesod

You can use multi-piece routes, and will likely need overlap checking turned off. This would look like: !/*Texts HomeR GET For more information, see the routing chapter of the Yesod book....

How do you add logic into the following `myApp` haskell function?

haskell,yesod,haskell-warp

myApp has this type: myApp :: Request -> (Response -> IO ResponseReceived) -> IO ResponseReceived so you can add your own IO action before returning the response like this: myApp _ respond = do putStrLn "processing request" respond $ responseLBS status200 [("Content-Type", "text/plain")] "Hello World" ...

How can I embed both Text and Widget in another Widget in Yesod?

haskell,yesod,hamlet

I wouldn't go this route, specifically because of the type inference issue you already discovered. Explicitly having to call toWidget occasionally is probably the best compromise here.

New yesod app not starting

haskell,yesod

Does /opt/cabal/1.20/bin contain version 1.20 of cabal? If so, put that directory in front of your PATH - i.e. replace the export PATH= in your .bashrc with: export PATH="/opt/cabal/1.20/bin:~/.cabal/bin:/opt/ghc/7.8.3/bin:$PATH" Reload your .bashrc and see what cabal sandbox --help reports....

how to break up the monolithic mkYesod block safely

haskell,module,hierarchy,yesod

You are correct, but that point is also addressed in the yesod book. For example have a look at http://www.yesodweb.com/book/scaffolding-and-the-site-template, the section called "Foundation and Application modules". Usually you have a Foundation module that defines route types and handler functions, and an Application module that defines the dispatching. So all...

Simplifying Persistent & Esqueleto code

haskell,yesod,persistent,esqueleto

Thanks to @JPMoresmau's hinting, I ended up with a much shorter, and I think simpler approach. It may be slower on large datasets due to nub, but on small datasets it returns far faster than I need it to. I still hate that I have so much manual plumbing to...

How can I query using persistent-mysql using withMySQLConn?

mysql,database,haskell,yesod,persistent

You're almost there. You just need to use one of the functions from monad-logger to provide a MonadLogger context. You may want to try runStdoutLoggingT.

Yesod: Stuck in book “Seven Web frameworks in seven weeks”

haskell,yesod

The instructions in this quick start guide led you to create a sandbox for your project, thus the dependencies you installed are only available within this sandbox (which is the cautious and arguably correct way to do it, avoiding collisions and easing the cleanup). GHCi is part of GHC and...

`defaultYesodMiddleware` and `authorizationCheck` are part of a hidden package, is there any way to reuse these?

module,dry,yesod,middleware

This is just a case where I forgot to expose the identifiers. Version 1.2.14 of yesod-core includes these two functions.

How to Use Group By and Sum in an Esqueleto Query

haskell,yesod,esqueleto

The from table parameters types are sometimes deduced from the result type which must be explicit. Other ambiguities arise about the monad type usually. It is useful to enclose the query in a specific function to solve some ambiguities. I cannot certify your esqueleto query conformity now but Try this:...

What are hsfiles? Why use a “.hsfiles” extension instead of a regular “.hs”?

haskell,yesod

You can see here the relevant code: backendBS :: Backend -> S.ByteString backendBS Sqlite = $(embedFile "hsfiles/sqlite.hsfiles") backendBS Postgresql = $(embedFile "hsfiles/postgres.hsfiles") backendBS PostgresqlFay = $(embedFile "hsfiles/postgres-fay.hsfiles") backendBS Mysql = $(embedFile "hsfiles/mysql.hsfiles") backendBS MongoDB = $(embedFile "hsfiles/mongo.hsfiles") backendBS Simple = $(embedFile "hsfiles/simple.hsfiles") backendBS Minimal = $(embedFile "hsfiles/minimal.hsfiles") So, it's used...

A typeclass instance that needs configuration data. What are my options?

haskell,configuration,yesod,typeclass

I'm going to simplify the problem so that we only need core libraries. We want to change how we Show a MarkdownText based on some ExampleSettings that contain a prefix and a suffix. {-# LANGUAGE OverloadedStrings #-} import Data.Text as T import Data.Monoid import Data.String newtype MarkdownText = MarkdownText {...

How do I derive PersistField for a custom newtype?

haskell,yesod

A PersistField isn't the same as a Field. You want to make a custom field by importing Yesod.Forms. Here's an example, for a MathJax type ;) newtype MathJax = MathJax { unMathJax :: Markdown } deriving (Eq, Ord, Show, Read, PersistField, PersistFieldSql, IsString, Monoid) unMM :: MathJax -> Text unMM...

Yesod errors when compiling

haskell,yesod

1 - Double example - set default value at field and for whole personeForm: data Person = Person { name :: Text , age :: Maybe Int } personeForm :: Maybe Person -> AForm Handler Person personeForm person = Person <$> areq textField "Persone Name" (name <$> person) <*> aopt...

Is there a Yesod alternative to the Rails' `link_to foo, bar, method: “delete”?

haskell,yesod

Here's an implementation of roughly what Rails is doing. This involves several parts: generating the link, using Javascript to implement the method changing functionality, and extra code for CSRF protection on the backend. Here's the linking aspect: linkToPost :: Route App -> [(Text,Text)] -> Text -> Widget linkToPost = linkToMethod...

Yesod CSS lucius

html,css,twitter-bootstrap,yesod

I got it. It was simple. The change was to be made to the input tag. So I added the following to my lucius file input { width:3em; } which was allowing me to control the width. ...

Haskell Noob: QuasiQuotes OverloadedStrings in Yesod not Working?

haskell,yesod

The putStrLn from ClassyPrelude takes a Text, not a String. The simplest solution would be to change the Renderer import to the Text version of the module.

Regular Expression on Yesod type Text

haskell,yesod,hackage

Have you taken a look at the regex-tdfa-text package? It provides backend support for using the regex-base library with Text strings.

Wildcard character asterisk in route path throws error

haskell,yesod

you have to add an type that is an instance of PathMultiPiece after the * like this: /*Texts HomeR GET (Texts, which is just a synonym for [Text] is an instance because Text is an instance of PathPiece) and of course you have to add it as an argument to...

use cabal2nix to create local nix environment for packages that aren't in nixpkgs

haskell,yesod,cabal-install,nixos

I was able to get this working after using the method on O'Charles' Nix wiki. I have not determined why this method was not working before. Basically, first run cabal2nix. Then create a generic shell.nix (that can be shared between all Haskell packages). $ cabal2nix --jailbreak --sha256=X ./$cabal > default.nix...

Yesod - how to make addScriptRemote add the script in the head section?

haskell,yesod,script-tag,yesod-forms

Where scripts get placed will depend on jsLoader. If you want to make a change for a specific script, you can use toWidgetHead [hamlet|<script src=...">|].

where does ^{pageBody pc} come from?

haskell,yesod

Hoogle on stackage.org is a great resource for these kinds of questions: http://www.stackage.org/lts/hoogle?q=pageBody...

Yesod Binary Unavailable

osx,haskell,cabal,yesod

Why did cabal fail to create a yesod binary? How do I fix this install? The yesod binary isn't part of the yesod package anymore. Instead, it has been extracted into the yesod-bin package: cabal install yesod-bin The binary should be in ~/Library/Haskell/bin, however, I'm not an OSX user....

Calling Haskell function in Yesod with onclick

haskell,yesod

Not directly the way you are describing. You can have onclick use some Javascript to make an AJAX call, which will trigger a handler function to be run.

How to specify type for class constrained value?

haskell,yesod,typeclass,persistent,monad-transformers

Turns out I didn't realize you needed to repeat constraints inside of functions as well. This worked: _ <- rawSql "SELECT ?? FROM my_entities WHERE id = ? FOR UPDATE" [toPersistValue somethingId] :: MonadIO m => SqlPersistT m [Entity MyEntity] ...

Joining with Maybe Fields

haskell,yesod,esqueleto

This query works. The difference between the query I had posted in my question and this one is really the ?. I thought I tried that variation but perhaps missed the obvious. I am still unclear when we will use ?. though. . I noticed I also get a working...