TWSViewMustacheExample

fun TWSViewMustacheExample(twsMustacheViewModel: TWSMustacheViewModel = hiltViewModel())

Demonstrates how to use the Mustache engine with TWSView in combination with local properties on the snippet.

If the TWSSnippet has its engine set to TWSEngine.Mustache, all properties defined in the props are used for Mustache template processing. This allows you to dynamically render content based on the provided data.

In this example, we showcase how to add additional local properties to the snippet using the manager. All new properties are added to the existing props (which are defined on the snippet details page on our platform), demonstrating how to extend the snippet's properties dynamically at runtime.

You can see a working example here. Download the Sample app from our web page to explore this functionality interactively.

Hint: try changing the props on howToMustache snippet and observe changes in the app instantly.

Samples

import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.res.stringResource
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.thewebsnippet.data.TWSSnippet
import com.thewebsnippet.manager.core.TWSManager
import com.thewebsnippet.manager.core.TWSOutcome
import com.thewebsnippet.manager.core.mapData
import com.thewebsnippet.sample.components.ErrorView
import com.thewebsnippet.sample.components.LoadingView
import com.thewebsnippet.sample.components.TWSViewComponentWithPager
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.collections.immutable.toImmutableList
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject

fun main() { 
   //sampleStart 
   // Set local properties
LaunchedEffect(Unit) {
    val localProps =
        mapOf(
            "welcome_email" to
                mapOf(
                    "name" to "Alice",
                    "company" to "TheWebSnippet",
                    "guide_url" to "https://mustache.github.io",
                    "community_name" to "TWS dev team",
                    "support_email" to "support@TWS.com"
                )
        )
    twsMustacheViewModel.setProps("howToMustache", localProps)
}

// Collect snippets for your project
val content = twsMustacheViewModel.twsSnippetsFlow.collectAsStateWithLifecycle(null).value

content?.let {
    when {
        !content.data.isNullOrEmpty() -> {
            val data = content.data ?: return
            TWSViewComponentWithPager(data.toImmutableList())
        }

        content is TWSOutcome.Error -> {
            ErrorView(content.exception.message ?: stringResource(R.string.error_message))
        }

        content is TWSOutcome.Progress -> {
            LoadingView()
        }
    }
} 
   //sampleEnd
}