A simple string substitution library that supports "$"-based substitution. Substitution uses the following rules:
- "$$" is an escape; it is replaced with a single "$".
- "$identifier" names a substitution placeholder matching a mapping key of "identifier". "identifier" must spell a Haskell identifier. The first non-identifier character after the "$" character terminates this placeholder specification.
- "${identifier}" is equivalent to "$identifier". It is required when valid identifier characters follow the placeholder but are not part of the placeholder, such as "${noun}ification".
Any other apperance of "$" in the string will result in an
error
being raised.
Here is an example of a simple substitution:
import qualified Data.ByteString.Lazy.Char8 as B import Text.Template context = Map.fromList . map packPair where packPair (x, y) = (B.pack x, B.pack y) helloTemplate = B.pack "Hello, $name! Want some ${fruit}s?" helloContext = context [("name", "Johan"), ("fruit", "banana")] main = B.putStrLn $ substitute helloTemplate helloContext
If you render the same template multiple times it's faster to first
convert it to a more efficient representation using template
and
then rendering it using render
. In fact, all that substitute
does
is to combine these two steps.
- data Template
- type Context = Map ByteString ByteString
- template :: ByteString -> Template
- render :: Template -> Context -> ByteString
- substitute :: ByteString -> Context -> ByteString
- showTemplate :: Template -> ByteString
- readTemplate :: FilePath -> IO Template
- renderToFile :: FilePath -> Template -> Context -> IO ()
- hRender :: Handle -> Template -> Context -> IO ()
The Template
type.
A repesentation of a ByteString
template, supporting efficient rendering.
The Context
type.
type Context = Map ByteString ByteStringSource
A mapping with keys that match the placeholders in the template.
Basic interface
template :: ByteString -> TemplateSource
Creates a template from a template string.
render :: Template -> Context -> ByteStringSource
Performs the template substitution, returning a new
ByteString
.
If a key is not found in the context an error
is raised.
substitute :: ByteString -> Context -> ByteStringSource
Performs the template substitution, returning a new
ByteString
. Note that
substitute tmpl ctx == render (template tmpl) ctx
If a key is not found in the context an error
is raised.
showTemplate :: Template -> ByteStringSource
Shows the template string.
I/O with Template
s
Files
readTemplate :: FilePath -> IO TemplateSource
Reads a template from a file lazily. Use 'text mode' on Windows to interpret newlines
renderToFile :: FilePath -> Template -> Context -> IO ()Source
Renders and writes a template to a file. This is more efficient
than first render
ing the template to a
ByteString
and then writing it to a file
using Data.ByteString.Lazy.Char8.writeFile
.