Moodle for latex
The snippet can be accessed without any authentication.
Authored by
HUIN Nicolas
Lua script to print moodle quiz as latex exam question
moodle.lua 2.88 KiB
-- moodle.lua
local dom = require("luaxml-domobject")
function print_from_html(text)
local dom_obj = dom.parse(text)
for _, children in ipairs(dom_obj:root_node():get_children()) do
if children:get_element_name() == 'p' then
tex.print(children:get_text() .. "\\\\")
elseif children:get_element_name() ~= 'unnamed' then
print(children:get_element_name() .. " -> Not supported yet")
end
end
end
function print_numerical(node, type)
local question_data = {}
question_data['answers'] = {}
for _, info in ipairs(node:get_children()) do
if info:get_element_name() == "questiontext" then
question_data['text'] = info:get_text()
end
if info:get_element_name() == "answer" then
if info:get_attribute('fraction') == '100' then
question_data['answer'] = info:get_text()
end
end
end
tex.print("\\begin{" .. type .. "}")
print_from_html(question_data['text'])
tex.print("\\begin{solutionorlines}[4em]")
tex.print(question_data['answer'])
tex.print("\\end{solutionorlines}")
tex.print("\\end{" .. type .. "}")
end
function print_multichoice(node, type)
local question_data = {}
question_data['answers'] = {}
for _, info in ipairs(node:get_children()) do
if info:get_element_name() == "questiontext" then
question_data['text'] = info:get_text()
end
if info:get_element_name() == "answer" then
local choice = nil
if info:get_attribute('fraction') == '100' then
choice = '\\CorrectChoice{' .. info:get_text() .. "}"
else
choice = '\\choice{' .. info:get_text() .. "}"
end
question_data['answers'][# question_data['answers'] + 1] = choice
end
end
tex.print("\\begin{" .. type .. "}")
tex.print(question_data['text'])
tex.print("\\begin{checkboxes}")
for _, answer in ipairs(question_data['answers']) do
tex.print(answer)
end
tex.print("\\end{checkboxes}")
tex.print("\\end{" .. type .. "}")
end
function print_moodle_question(filename, question_level)
-- Read the XML data from an external file (e.g., "quiz.xml")
local file = io.open(filename)
if file == nil then
return
end
local xml_data = file:read("*all")
file:close()
-- Now parse and output the quiz data
local obj = dom.parse(xml_data)
local root_node = obj:root_node()
for _, quiz in ipairs(root_node:get_children()) do
for _, question in ipairs(quiz:get_children()) do
if question:get_attribute("type") == "multichoice" then
print_multichoice(question, question_level)
end
if question:get_attribute("type") == "numerical" then
print_numerical(question, question_level)
end
end
end
end
Please register or sign in to comment