Module:URL: Difference between revisions
From Zoophilia Wiki
Jump to navigationJump to search
meta>Toohool preserve case in a query string or anchor without a path |
meta>Toohool add comment |
||
Line 1: | Line 1: | ||
-- | |||
-- This module implements {{URL}} | |||
-- | |||
local p = {} | local p = {} | ||
Revision as of 04:14, 22 February 2013
Documentation for this module may be created at Module:URL/doc
--
-- This module implements {{URL}}
--
local p = {}
function trim(s)
if s == nil then return '' end
return (s:gsub("^%s*(.-)%s*$", "%1"))
end
function startsWith(s, prefix)
return (s:find(prefix, 1, true)) == 1
end
function split(s, sep) -- string split function for a single-character separator
local ret = {}
local n = 1
for w in s:gmatch("([^" .. sep .. "]*)") do
ret[n] = ret[n] or w -- only set once (so the blank after a string is ignored)
if w == '' then n = n + 1 end -- step forwards on a blank but not a string
end
return ret
end
function rest(tbl, start) -- get the elements of the table beginning at the specified starting index
local ret = {}
if start > #tbl then
return ret
end
for i = start, #tbl do
ret[i - start + 1] = tbl[i]
end
return ret
end
function p._url(url, text)
local lcUrl = url:lower()
if not startsWith(lcUrl, 'http://') and not startsWith(lcUrl, 'https://') and not startsWith(lcUrl, 'ftp://') then
url = 'http://' .. url
end
if text == '' then
local comps = split(url, '/')
local host = comps[3]
local path = table.concat(rest(comps, 4), '/')
local idx = host:find('?') or host:find('#') -- if there's a query string or anchor directly after the host name, without the default path ("/") in between, its case should be preserved
if idx == nil then
host = host:lower()
else
host = host:sub(1, idx - 1):lower() .. host:sub(idx)
end
text = host
if path ~= '' then
text = text .. '/' .. path
end
end
return string.format('<span class="url">[%s %s]</span>', url, text)
end
function p.url(frame)
local url = trim(frame.args[1])
local text = trim(frame.args[2])
if url == '' then
if text == '' then
return frame:expandTemplate{ title = 'tlx', args = { 'URL', "''example.com''", "''optional display text''" } }
else
url = text
end
end
return p._url(url, text)
end
return p