Kotlin DSL
Kotlin DSL is a tool for describing UI in DivKit format using Kotlin language.
Usage
A typical process of working with the library is as follows.
- Building layout as a
divan
object.Data
class has structure ofdiv-data
with a number of helper extension functions.
val card = divan {
data(
// card id, required property
logId = "new-div-card",
// Card visual content declaration.
// In this case the card contains one text element.
div = text(
fontSize = 18,
text = "Hello, world!"
)
)
}
divan
object serialization into JSON. In the following examplecom.fasterxml.jackson
library is used.
val jsonString = JsonMapper.builder().build().writeValueAsString(card)
- Sending the acquired JSON to the client.
Examples
Expressions in the UI element properties
To set an expression as the element property value use evaluate
extension function.
val card = divan {
data(
logId = "new-div-card",
// variables declaration
variables = listOf(
stringVariable(
name = "hello_text",
value = "Hello, world!"
)
),
div = text(
// constant properties declaration
fontSize = 18
).evaluate(
// expression properties declaration
text = expression("@{hello_text}")
)
)
}
Templates
// reference property declaration
val titleRef = reference<String>("title")
// template declaration
val titleTemplate = template("title_text") {
text(
// template constant properties declaration
fontSize = 18,
width = wrapContentSize(),
) + textRefs(
// template reference properties declaration
text = titleRef
)
}
val card = divan {
data(
logId = "new-div-card",
div = container(
orientation = vertical,
items = listOf(
// creating an element using the template
render(
titleTemplate,
// setting the value into the reference property
titleRef bind "Hello, world!"
) + textProps(
// base properties declaration/overriding
fontSize = 20
),
// creating one more element using the same template
render(
titleTemplate,
titleRef bind "Hello, DivKit!"
)
)
)
)
}
Learn more
Follow DivKit news in the Telegram channel: http://t.me/divkit_news
You can also discuss topics of interest in the DivKit user community in Telegram: https://t.me/divkit_community_ru
Was the article helpful?
Previous
Next