summaryrefslogtreecommitdiff
path: root/src/Hakyll/Web/Urls/Relativize.hs
blob: 0251cfe756ea56857c8573c3ac6ebbe2d39cef28 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
--------------------------------------------------------------------------------
-- | This module exposes a function which can relativize URL's on a webpage.
--
-- This means that one can deploy the resulting site on
-- @http:\/\/example.com\/@, but also on @http:\/\/example.com\/some-folder\/@
-- without having to change anything (simply copy over the files).
--
-- To use it, you should use absolute URL's from the site root everywhere. For
-- example, use
--
-- > <img src="/images/lolcat.png" alt="Funny zomgroflcopter" />
--
-- in a blogpost. When running this through the relativize URL's module, this
-- will result in (suppose your blogpost is located at @\/posts\/foo.html@:
--
-- > <img src="../images/lolcat.png" alt="Funny zomgroflcopter" />
module Hakyll.Web.Urls.Relativize
    ( relativizeUrlsCompiler
    , relativizeUrls
    ) where


--------------------------------------------------------------------------------
import           Control.Arrow        ((&&&), (>>^))
import           Control.Category     (id)
import           Data.List            (isPrefixOf)
import           Prelude              hiding (id)


--------------------------------------------------------------------------------
import           Hakyll.Core.Compiler
import           Hakyll.Web.Page
import           Hakyll.Web.Urls


--------------------------------------------------------------------------------
-- | Compiler form of 'relativizeUrls' which automatically picks the right root
-- path
relativizeUrlsCompiler :: Compiler Page Page
relativizeUrlsCompiler = getRoute &&& id >>^ uncurry relativize
  where
    relativize Nothing  = id
    relativize (Just r) = relativizeUrls $ toSiteRoot r


--------------------------------------------------------------------------------
-- | Relativize URL's in HTML
relativizeUrls :: String  -- ^ Path to the site root
               -> Page    -- ^ HTML to relativize
               -> Page    -- ^ Resulting HTML
relativizeUrls root = withUrls rel
  where
    isRel x = "/" `isPrefixOf` x && not ("//" `isPrefixOf` x)
    rel x   = if isRel x then root ++ x else x