Module:Section link: Difference between revisions
m>Mr. Stradivarius (create replacement for Template:Section link) |
(No difference)
|
Revision as of 07:03, 9 December 2014
Documentation for this module may be created at Module:Section link/doc
-- This module implements {{section link}}. local checkType = require('libraryUtil').checkType local p = {} local function makeWikitextError(msg) return string.format( '<strong class="error">[[Template:Section link]] error: %s.</strong>', msg ) end local function makeSectionLink(page, section, display) display = display or section page = page or '' return string.format('[[%s#%s|%s]]', page, section, display) end function p._main(page, sections, options, title) -- Validate input. checkType('_main', 1, page, 'string', true) checkType('_main', 3, options, 'table', true) if type(sections) == 'string' then sections = {sections} elseif type(sections) ~= 'table' then error(string.format( "type error in argument #2 to '_main' (string or table expected, got %s)", type(sections) ), 2) end options = options or {} title = title or mw.title.getCurrentTitle() if #sections < 1 then return makeWikitextError('at least one section must be specified') end -- Make the link(s). local isShowingPage = not options.nopage if #sections == 1 then local linkPage = page or '' local section = sections[1] or 'Notes' local display = '§ ' .. section if isShowingPage then page = page or title.prefixedText display = page .. ' ' .. display end return makeSectionLink(linkPage, section, display) else -- Multiple sections. First, make the list of links. local ret = {} for i, section in ipairs(sections) do ret[i] = makeSectionLink(page, section) end -- Assemble the list of links into a string with mw.text.listToText. -- We use the default arguments for mw.text.listToText, unless we have -- exactly two sections, in which case we use a custom conjunction. local conjunction if #sections == 2 then conjunction = '​ and ' end ret = mw.text.listToText(ret, nil, conjunction) -- Add the intro text. local intro = '§§ ' if isShowingPage then intro = (page or title.prefixedText) .. ' ' .. intro end ret = intro .. ret return ret end end function p.main(frame) local args = require('Module:Arguments').getArgs(frame, { wrappers = 'Template:Section link' }) -- Sort the arguments. local page local sections, options = {}, {} for k, v in pairs(args) do if k == 1 then -- Doing this in the loop because of a bug in [[Module:Arguments]] -- when using pairs with deleted arguments. page = v elseif type(k) == 'number' then sections[k] = v else options[k] = v end end -- Compress the sections array. local function compressArray(t) local nums, ret = {}, {} for num in pairs(t) do nums[#nums + 1] = num end table.sort(nums) for i, num in ipairs(nums) do ret[i] = t[num] end return ret end sections = compressArray(sections) return p._main(page, sections, options) end return p