import{_ as i,a,b as n,ag as l}from"./chunks/framework.BcrMLAmg.js";const g=JSON.parse('{"title":"XML in Basalt","description":"","frontmatter":{},"headers":[],"relativePath":"guides/xml.md","filePath":"guides/xml.md","lastUpdated":1740474136000}'),t={name:"guides/xml.md"};function h(p,s,e,k,E,r){return n(),a("div",null,s[0]||(s[0]=[l(`
Basalt provides an XML parser that lets you define your UI layout in a declarative way. This can make your code more readable and maintainable.
local main = basalt.getMainFrame()
-- Load from file
local xmlFile = fs.open("myUI.xml", "r")
main:loadXML(xmlFile.readAll())
xmlFile.close()
-- Or directly as string
main:loadXML([[
<frame width="30" height="10">
<button text="Click me!" x="2" y="2"/>
</frame>
]])The XML parser uses a scope system to access variables and functions. Any variables you want to use in your XML must be passed in the scope:
local scope = {
title = "My App",
buttonWidth = 10,
handleClick = function(self)
self:setText("Clicked!")
end
}
main:loadXML([[
<frame>
<label text="\${title}"/>
<button width="\${buttonWidth}" onClick="handleClick"/>
</frame>
]], scope)There are two ways to define event handlers:
local scope = {
btnClick = function(self)
self:setText("Clicked!")
end
}
main:loadXML([[
<button onClick="btnClick"/>
]], scope)<button>
<onClick>
<![CDATA[
function(self)
self:setText("Clicked!")
end
]]>
</onClick>
</button>The XML parser automatically converts values based on the property type:
<button
x="5" <!-- Converted to number -->
visible="true" <!-- Converted to boolean -->
background="blue" <!-- Converted to colors.blue -->
text="\${title}" <!-- Evaluated from scope -->
/>Scope Variables
Event Handlers
Expressions
\${...} for scope accesslocal scope = {
appTitle = "My App",
colors = colors,
handleSubmit = function(self)
-- handle submission
end
}
local xmlFile = fs.open("example.xml", "r")
main:loadXML(xmlFile.readAll(), scope)
xmlFile.close()<frame background="\${colors.gray}">
<label
x="2" y="2"
text="\${appTitle}"
/>
<button
x="2" y="4"
text="Submit"
onClick="handleSubmit"
/>
<button x="2" y="6">
<onClick>
<![CDATA[
function(self)
self:getParent():remove()
end
]]>
</onClick>
</button>
</frame>