Jump to content

Module:TOCyears

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Mr. Stradivarius (talk | contribs) at 04:59, 3 October 2014 (add a function to replace Template:TOCyears, add a makeWikilink function, make a few bug fixes, and add a workaround for bugzilla:71594). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

-- This module implements various templates that create custom tables of
-- contents.

-- Load necessary modules
local yesno = require('Module:Yesno')
local checkType = require('libraryUtil').checkType

local p = {}

local function makeWikilink(page, display)
	if display then
		return string.format('[[%s|%s]]', page, display)
	else
		return string.format('[[%s]]', page)
	end
end

local function makeToc(s, args)
	-- Make a TOC box from a string and from the given table of arguments.
	checkType('makeToc', 1, s, 'string')
	checkType('makeToc', 2, args, 'table', true)
	args = args or {}

	-- Root
	local root = mw.html.create()
	local isPrimary = yesno(args.primary) ~= false
	if isPrimary then
		root:wikitext('__NOTOC__')
	end

	-- Top div tag
	local top = root:tag('div')
	top:addClass('toc plainlinks hlist')
	if isPrimary then
		top:attr('id', 'toc')
	end
	local align = args.align and args.align:lower()
	if align == 'left' then
		top
			:css('float', 'left')
			:css('clear', args.clear or 'left')
	elseif align == 'right' then
		top
			:css('float', 'right')
			:css('clear', args.clear or 'right')
	elseif align == 'center' then
		top
			:css('margin', 'auto')
			:css('clear', args.clear or 'none')
	else
		top
			:css('clear', args.clear or 'left')
	end
	top:newline()

	-- Title div tag
	local title = args.title or mw.message.new('Toc'):plain()
	local titleDiv = top:tag('div')
	titleDiv:attr('id', 'toctitle')
	if isPrimary then
		titleDiv:wikitext('<h2>' .. title .. '</h2>')
	else
		titleDiv:tag('strong'):wikitext(title)
	end
	
	-- Content
	top
		:wikitext(s)
		:newline()
	
	return tostring(root)
end

p.makeToc = makeToc

function p.year(args)
	local i = tonumber(args.startyear) or 1900
	local endYear = tonumber(args.endyear) or 1950
	local range = tonumber(args.range)
	local step = tonumber(args.step) or 1
	local links = {}
	while i <= endYear do
		local year = tostring(i)
		if range then
			year = year .. '-' .. tostring(i + range)
		end
		links[#links + 1] = '* ' .. makeWikilink('#' .. year, year)
		i = i + step
	end
	links = '\n' .. table.concat(links, '\n')
	return makeToc(links, args)
end

return p