Micro Template 📃 A very tiny and simple text templating library for Kotlin.

Overview

Micro Template 📃

A very tiny and simple text templating library for Kotlin. It has very limited features, so it's intended to be used for short templates that don't need any logic or advanced formatting. All it does is replace every named token (ex: {name}) with a matching value from a map (context), or provide a default for missing ones. Not suitable for rendering web views or pages, in general.

NOTE: It's not optimized for speed, but as long as you render short strings performance shouldn't be a problem.

Usage

A simple "hello" example:

// create a reusable template
val greeting = MicroTemplate("Hello, {name}!")

// the values to be applied define a 'context'
val context = mapOf("name" to "Matteo")
greeting(context) // Hello, Matteo!

A context can contain values of any type:

// raw strings make multi-line templates more readable
val status = MicroTemplate(
    """
    Welcome back {user}! 
    You have {messages} unread messages. 
    Your crypto balance is: {balance}
    """
)

val context = mapOf(
    "user" to "Tom",
    "messages" to 99,
    "balance" to Coin(10_000)
)
status(context) //  Welcome back Tom! 
                //  You have 99 unread messages.
                //  Your crypto balance is: 10000ÂĐ

Handling missing values:

()) // "Hello, !" // you can set a default value for the whole template val scores = MicroTemplate( """ Leaderboard --- Team A {scoreA} Team B {scoreB} Team C {scoreC} """, default = "N/A" ) scores(mapOf("scoreA" to 99)) // Leaderboard // --- // Team A 99 // Team B N/A // Team C N/A // or you can specify a default for a token val greeting = MicroTemplate("Hello, {title:Buana }{name}!") val context = mapOf ("name" to "Matteo") greeting(context) shouldBe "Hello, Buana Matteo!" ">
// by default missing values are replaced with an empty string
val greeting = MicroTemplate("Hello, {name}!")
greeting(emptyMap<String, Any>()) // "Hello, !"

// you can set a default value for the whole template
val scores = MicroTemplate(
    """
    Leaderboard
    ---
    Team A      {scoreA}
    Team B      {scoreB}
    Team C      {scoreC}
    """,
    default = "N/A"
)
scores(mapOf("scoreA" to 99)) // Leaderboard
                              // ---
                              // Team A      99
                              // Team B      N/A
                              // Team C      N/A

// or you can specify a default for a token
val greeting = MicroTemplate("Hello, {title:Buana }{name}!")
val context = mapOf<String, Any>("name" to "Matteo")
greeting(context) shouldBe "Hello, Buana Matteo!"

Features

Current features:

  • basic token interpolation
  • all types are converted using their toString() function
  • missing values are replaced with an empty string by default
  • a custom default value can be configured globally or per token

Micro Template is useful if you need a quick and basic template support, hard-coded in your source code (it doesn't support loading template files).

It does not support:

  • custom formatting
  • logic (no conditional or loops)
  • functions or code execution
  • template composition or inclusion
  • sub-templates/macros
  • nested interpolation (ex: {{name}})
  • loading templates from external files

Motivation

Why use this library if Kotlin already has built-in support for string templates? The problem with template expressions is that they can't be created and used dynamically, since they are evaluated at compile time, so their bindings (context) must be visible in the scope of their declaration.

Evaluation happens eagerly at compile time:

this doesn't compile! val template = "$foo is like $bar" ">
val i = 10
println("i = $i") // OK, 'i' is visible in this scope

// you can't store a string template for later reuse
// --> this doesn't compile!
val template = "$foo is like $bar"

To achieve lazy usage, we could wrap the template in a lambda:

val template = { foo:String, bar:Int -> "$foo is like $bar" }

template("The Answer", 42) // The Answer is like 42

this is better, but you still have to declare the template in your code, so you can't create it dynamically from a string or resource:

val template = readFromFile("view.tpl") // contains the text 'Hello, ${user}!'
template.? // what do we do now? 

This behavior can be enough for many applications, but it's still limiting. We could try and compile the code for a template lambda at runtime to circumvent this limitation, but it seems overkill for a simple text substitution matter. Anyway, even if feasible, we must provide all of its bindings explicitly as parameters, or it won't compile again.

Instead, using a simple solution like micro-template, you can dynamically create a template and apply it lazily, passing arbitrary parameters.

Distribution

This library is contained in a single file and has no 3rd-party dependencies, so you can just copy it directly into your project.

TODO

For the list of next features, see the TODO kanban.

You might also like...
Androids EditText that animates the typed text. EditText is extended to create AnimatedEditText and a PinEntryEditText.
Androids EditText that animates the typed text. EditText is extended to create AnimatedEditText and a PinEntryEditText.

AnimatedEditText for Android This repository contains AnimatedEditText and TextDrawable all of which extend the behaviour of EditText and implement fe

Add text masking functionality to Android EditText. It will prevent user from inserting not allowed signs, and format input as well.
Add text masking functionality to Android EditText. It will prevent user from inserting not allowed signs, and format input as well.

MaskFormatter MaskFormatter adds mask functionality to your EditText. It will prevent user from inserting not allowed signs, and format input as well.

RichEditor for Android is a beautiful Rich Text WYSIWYG Editor for Android.
RichEditor for Android is a beautiful Rich Text WYSIWYG Editor for Android.

RichEditor for Android is a beautiful Rich Text WYSIWYG Editor for Android. Looking for iOS? Check out cjwirth/RichEditorView Supported Functions Bold

Animation effects to text, not really textview
Animation effects to text, not really textview

HTextView Animation effects with custom font support to TextView see iOS Effects see Flutter Effects Screenshot type gif Scale Evaporate Fall Line Typ

A TextView that automatically resizes text to fit perfectly within its bounds.
A TextView that automatically resizes text to fit perfectly within its bounds.

AutoFitTextView A TextView that automatically resizes text to fit perfectly within its bounds. Usage dependencies { compile 'me.grantland:autofitt

:page_facing_up: Android Text Full Jusiftication / Wrapping / Justify / Hyphenate - V2.0
:page_facing_up: Android Text Full Jusiftication / Wrapping / Justify / Hyphenate - V2.0

LIBRARY IS NO LONGER MAINTAINED If you want to adopt + maintain this library, please drop me a message - [email protected] Android Full Justific

Android form edit text is an extension of EditText that brings data validation facilities to the edittext.
Android form edit text is an extension of EditText that brings data validation facilities to the edittext.

Android Form EditText Android form edit text is an extension of EditText that brings data validation facilities to the edittext. Example App I built a

A Custom TextView with trim text
A Custom TextView with trim text

ReadMoreTextView A Custom TextView with trim text Download To add the ReadMoreTextView library to your Android Studio project, simply add the followin

[DISCONTINUED] Rrich text editor for android platform. åŪ‰å“åŊŒæ–‡æœŽįž–čū‘å™Ļ暂停įŧīæŠĪ

icarus-android Maybe the best rich text editor on android platform. Base on Simditor Features Alignment (left/center/right) Bold Blockquote Code Horiz

Comments
  • Feature/configuration dsl

    Feature/configuration dsl

    Introduces a builder lambda for configuring a template when using factory functions. All the setup properties and defaults are now in the Configuration class.

    Also, a bug was discovered: when invoking a typed template accepting a private class it would throw a runtime exception with a misleading message. The fix introduces an init check that fails earlier with an informative message.

    BREAKING CHANGE: MicroTemplate signature has changed to accept a Configuration parameter.

    opened by polarene 0
  • Feature/factory and interface

    Feature/factory and interface

    Added top-level factory functions to create template instances and decouple the client from concrete implementations. Existing classes have been retrofitted to a common interface Template<T>.

    opened by polarene 0
  • Feature/escaping

    Feature/escaping

    Supports the escaping of reserved characters {} inside a template text or token default value so that they can be rendered verbatim, without being interpolated.

    Ref: https://github.com/polarene/micro-template/projects/1#card-70958277

    hacktoberfest-accepted 
    opened by polarene 0
Releases(v0.4.0)
Owner
Matteo Mirk
Matteo Mirk
RTL marquee text view android right to left moving text - persian - farsi - arabic - urdo

RTL marquee text view android right to left moving text - persian - farsi - arabic - urdo

mehran elyasi 4 Feb 14, 2022
A simple library for hide and show text with animation.

ViewMore TextView ViewMore TextView allows you to use a TextView by hiding the content of the text by a number of established lines and to display all

Michele Quintavalle 81 Dec 23, 2022
Irineu A. Silva 2 Feb 17, 2022
A simple Android library to protect part of text using Span

Text Protector A simple Android library to "protect" part of text using Span What is this? This is a small library for replacing part of a text in a T

Oleg Nestyuk 4 May 16, 2022
Simple way to create linked text, such as @username or #hashtag, in Android TextView and EditText

Simple Linkable Text Simple way to create link text, such as @username or #hashtag, in Android TextView and EditText Installation Gradle Add dependenc

Aditya Pradana Sugiarto 76 Nov 29, 2022
Dealing with Android Text by simple way to get high performance.

Gapo Android RichText RichText supports Hashtag, Mention, Url, Phone Number, Email, Markdown, Custom Span, SeeMore/SeeLess by limited line or length,

GapoWork 8 Oct 20, 2021
Dealing with Android Text by simple way to get high performance.

Gapo Android RichText RichText supports Hashtag, Mention, Url, Phone Number, Email, Markdown, Custom Span, SeeMore/SeeLess by limited line or length,

GapoWork 8 Oct 20, 2021
Android library contain custom realisation of EditText component for masking and formatting input text

Masked-Edittext Masked-Edittext android library EditText widget wrapper add masking and formatting input text functionality. Install Maven <dependency

Evgeny Safronov 600 Nov 29, 2022
Chips EditText, Token EditText, Bubble EditText, Spannable EditText and etc.. There are many names of this control. Here I develop easy to understand , modify and integrate Chips Edit Text widget for Android

Chips EditText Library Chips EditText, Token EditText, Bubble EditText, Spannable EditText and etc.. There are many names of this control. Here I deve

kpbird 381 Nov 20, 2022
MarkdownView is an Android webview with the capablity of loading Markdown text or file and display it as HTML, it uses MarkdownJ and extends Android webview.

MarkdownView is an Android webview with the capablity of loading Markdown text or file and display it as HTML, it uses MarkdownJ and extends Android webview.

Feras Alnatsheh 1k Dec 20, 2022