]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - doc/tips/JavaScript_to_add_index.html_to_file:_links.mdwn
Added a comment: you can't use and/or/! inside the page() parameter, move them outside
[git.ikiwiki.info.git] / doc / tips / JavaScript_to_add_index.html_to_file:_links.mdwn
1 [[!meta date="2007-09-10 04:32:55 +0000"]]
3 The source file `foo/bar.mdwn` or `foo/bar.html` generates the
4 page `foo/bar/index.html`, but the links to the page appear
5 as "`foo/bar/`".  This is fine (and recommended) for pages
6 served by an http server, but it doesn't work when browsing
7 the pages directly using `file:` URL.  The latter might be
8 desirable when testing pages before upload, or if you want to
9 read pages when off-line without access to a web server.
11 Here is a JavaScript "`onload`" script which fixes the URLs
12 if the `local.protocol` isn't `http` or `https`:
14         function fixLinks() {
15           var scheme = location.protocol;
16          if (scheme=="http:" || scheme=="https:") return;
17          var links = document.getElementsByTagName("a");
18           for (var i = links.length; --i >= 0; ) {
19            var link = links[i];
20             var href = link.href;
21             var hlen = href.length;
22            if (hlen > 0 && link.protocol==scheme && href.charAt(hlen-1) == "/")
23              links[i].href = href + "index.html";
24           }
25         }
27 This can be placed in `page.tmpl`:
29         <html>
30         <head>
31         <script language="JavaScript">
32         function fixLinks() {
33         ...
34         }
35         </script>
36         </head>
37         <body onload="javascript:fixLinks();">
38         ...
39         </html>
41 This script has not been extensively tested.
43 ---
45 A version that handles anchors:
48         function fixLinks() {
49           var scheme = location.protocol;
50           if (scheme != "file:") return;
51           var links = document.getElementsByTagName("a");
52           for (var i = links.length; --i >= 0; ) {
53             var link = links[i];
54             var href = link.href;
55             var anchor = "";
56             var anchorIndex = href.indexOf("#");
57             if (anchorIndex != -1) {
58               anchor = href.substring(anchorIndex);
59               href = href.substring(0, anchorIndex);
60             };
61             var hlen = href.length;
62             if (hlen > 0 && link.protocol==scheme && href.charAt(hlen-1) == "/")
63               links[i].href = href + "index.html" + anchor;
64           }
65         }