### Render DOM Elements with scalatags.JsDom Source: https://context7.com/com-lihaoyi/scalatags/llms.txt Use the JsDom backend for Scala.js to render HTML directly to `dom.Element` objects. Call `.render` to get a live DOM node and append it to the document. ```scala import scalatags.JsDom.all._ import org.scalajs.dom // Renders to a real dom.HTMLDivElement val elem: dom.html.Div = div( h1("Hello"), p("World") ).render dom.document.body.appendChild(elem) // Binding a JS function directly to onclick (only possible in JsDom backend) var counter = 0 val btn = button( onclick := { () => counter += 1; println(s"Clicked $counter times") }, "Click me" ).render ``` -------------------------------- ### CSS Stylesheets with scalatags.stylesheet Source: https://context7.com/com-lihaoyi/scalatags/llms.txt Define typed CSS stylesheets as Scala objects extending `StyleSheet`. Classes are referenced by value in HTML fragments. Call `styleSheetText` to get the generated CSS string. ```Scala import scalatags.stylesheet._ import scalatags.Text.all._ object AppStyles extends StyleSheet { initStyleSheet() val button = cls( backgroundColor := "blue", color := "white", padding := "8px 16px", borderRadius := "4px" ) val buttonHover = cls.hover( opacity := 0.8 ) // Compose classes by splicing val primaryButton = cls(button.splice, buttonHover.splice) } // Use in HTML val page = div( button(AppStyles.button)("Normal Button"), button(AppStyles.primaryButton)("Primary Button") ) // Emit CSS to file/style tag println(AppStyles.styleSheetText) // .AppStyles-button{ background-color: blue; color: white; padding: 8px 16px; border-radius: 4px; } // .AppStyles-buttonHover:hover{ // opacity: 0.8; // } // .AppStyles-primaryButton{ background-color: blue; color: white; ... opacity: 0.8; } ``` -------------------------------- ### Applying Inline Styles with Typed Properties and css() Source: https://context7.com/com-lihaoyi/scalatags/llms.txt Demonstrates applying CSS styles using typed properties for static checking and the `css()` function for custom properties. Numeric pixel values are automatically suffixed with 'px'. ```Scala import scalatags.Text.all._ val styled = div( // Typed style properties h1(backgroundColor := "blue", color := "red")("Styled title"), // Numeric value — gets "px" suffix automatically div(width := 300, height := 200, zIndex := 10)( p(opacity := 0.75)("Semi-transparent") ), // Enumerated style values p(float.left, textAlign.center)("Floating paragraph"), // Custom CSS property span(css("text-shadow") := "1px 1px 2px black")("Shadowed"), // Raw style string as attribute div(style := "border: 1px solid; padding: 8px;")("Manual style") ) println(styled.render) ``` -------------------------------- ### Creating Reusable Components with Functions and Layouts Source: https://context7.com/com-lihaoyi/scalatags/llms.txt Illustrates how standard Scala functions can be used as reusable components and layout templates, accepting sequences of Modifiers for dynamic content. ```Scala import scalatags.Text.all._ // Reusable component function def imgBox(src: String, caption: String) = div(cls := "img-box")( img(`src` := src), p(cls := "caption")(caption) ) // Layout function accepting Modifier sequences def page(headScripts: Seq[Modifier], bodyContent: Seq[Modifier]) = html( head(headScripts), body( header(h1("My Site")), main(cls := "content")(bodyContent) ) ) val result = page( Seq(script(src := "/app.js")), Seq( imgBox("/photo1.jpg", "First photo"), imgBox("/photo2.jpg", "Second photo"), p("Some extra text") ) ) println(result.render) ``` -------------------------------- ### Class-based Inheritance for Template Layouts Source: https://context7.com/com-lihaoyi/scalatags/llms.txt Demonstrates using Scala's class inheritance to create a base page layout and extend it with specific overrides for different page types, like an admin page. ```Scala import scalatags.Text.all._ class BasePage { def render = html(headFrag, bodyFrag) def headFrag = head(script(src := "/base.js")) def bodyFrag = body(h1("Base Title"), p("Base content")) } object AdminPage extends BasePage { override def headFrag = head( script(src := "/base.js"), script(src := "/admin.js") ) override def bodyFrag = body( h1("Admin Dashboard"), div(cls := "admin-panel")("Admin tools here") ) } println(AdminPage.render.toString) ``` -------------------------------- ### Scalatags Import Strategies: `all`, `short`, Manual Source: https://context7.com/com-lihaoyi/scalatags/llms.txt Scalatags offers three import strategies: `all` imports everything, `short` imports tags and converters while placing attrs/styles under `*`, and manual import allows fine-grained aliasing to avoid namespace pollution. ```scala // Strategy 1: import everything import scalatags.Text.all._ div(color := "red")("content") // Strategy 2: short — access attrs/styles via `*` import scalatags.Text.short._ div(*.color := "red", *.fontSize := 16.pt)("content") // Strategy 3: manual aliasing to avoid namespace pollution import scalatags.Text.{attrs => at, styles => css, _} import scalatags.Text.tags._ import scalatags.Text.implicits._ div(css.color := "red", at.cls := "container")("content") // All three produce equivalent HTML output ``` -------------------------------- ### Cross-Backend Code with generic.Bundle Source: https://context7.com/com-lihaoyi/scalatags/llms.txt Write code that is generic over the backend by parameterizing on `Bundle[Builder, Output, FragT]`. The same templates compile for both `Text` (server-side strings) and `JsDom` (browser DOM). ```Scala import scalatags.generic.Bundle class SharedTemplates[Builder, Output <: FragT, FragT](val bundle: Bundle[Builder, Output, FragT]) { import bundle.all._ // Works identically for Text and JsDom def userCard(name: String, role: String, avatarUrl: String): Tag = div(cls := "user-card")( img(src := avatarUrl, alt := name), div(cls := "user-info")( h3(name), p(cls := "role")(role) ) ) } // Server-side: renders to String val textTemplates = new SharedTemplates(scalatags.Text) val htmlString = textTemplates.userCard("Alice", "Engineer", "/alice.png").render // =>
Alice
... // Client-side: renders to dom.Element (Scala.js only) // val domTemplates = new SharedTemplates(scalatags.JsDom) // val element = domTemplates.userCard("Alice", "Engineer", "/alice.png").render // dom.document.body.appendChild(element) ``` -------------------------------- ### Using Variables and Control Flow in Templates Source: https://context7.com/com-lihaoyi/scalatags/llms.txt Shows how Scala variables, expressions, for comprehensions, and if/else branches can be directly embedded within Scalatags templates without special syntax. ```Scala import scalatags.Text.all._ val posts = Seq( ("alice", "I like pie"), ("bob", "Pie is overrated"), ("charlie", "Pie is amazing and pie is life") ) val totalVisitors = 1023 val showBanner = totalVisitors > 100 val page = html( body( h1("Blog Posts"), for ((author, text) <- posts) yield div(cls := "post")( h2("Post by ", author), p(text) ), if (showBanner) p(cls := "notice")("Over 1000 visitors!") else p("Just getting started"), p("Total visitors: ", totalVisitors.toString) ) ) ``` -------------------------------- ### Create Custom Tags with tag() Source: https://context7.com/com-lihaoyi/scalatags/llms.txt Use the `tag(...)` function to create custom or non-standard HTML/XML tags by name. This is useful for formats like RSS, SVG, or custom elements. ```scala import scalatags.Text.all._ val rssXml = tag("rss")(attr("version") := "2.0")( tag("channel")( tag("title")("My Blog"), tag("link")("https://example.com"), tag("description")("A blog about things"), tag("item")( tag("title")("First Post"), tag("link")("https://example.com/post/1"), tag("pubDate")("Mon, 01 Jan 2024 00:00:00 GMT") ) ) ) println("" + rssXml.render) // My Blog... ``` -------------------------------- ### Generate HTML String with scalatags.Text Source: https://context7.com/com-lihaoyi/scalatags/llms.txt Use the Text backend to generate HTML as a String. Import `scalatags.Text.all._` and call `.toString` or `.render` on the generated tag. ```scala import scalatags.Text.all._ val page = html( head( script(src := "app.js"), script("alert('Hello World')") ), body( div( h1(id := "title", "This is a title"), p("This is a paragraph of text") ) ) ) println(page.toString) // //

This is a title

This is a paragraph of text

``` -------------------------------- ### Define Custom Scalatags Bundles Source: https://context7.com/com-lihaoyi/scalatags/llms.txt Create a custom bundle object to establish project-wide import conventions, defining exactly where tags, attributes, and styles are placed. This promotes consistency across your project. ```scala import scalatags.Text import scalatags.text object MyBundle extends Text.Cap with text.Tags with text.Tags2 with Text.Aggregate { object st extends Text.Cap with Text.Styles with Text.Styles2 object at extends Text.Cap with Text.Attrs } import MyBundle._ val page = html( head(script("some script")), body( h1(st.backgroundColor := "blue", st.color := "white")("Title"), div(at.cls := "container")( p(st.fontSize := 16.px)("Hello world") ) ) ) println(page.render) // //

Title

//

Hello world

``` -------------------------------- ### CSS Inline Pseudo-Selectors Source: https://context7.com/com-lihaoyi/scalatags/llms.txt Use `&.hover(...)`, `&.active(...)` etc. inside a `cls(...)` definition to add pseudo-selector rules without defining a separate class. ```Scala import scalatags.stylesheet._ import scalatags.Text.all._ object ButtonStyles extends StyleSheet { initStyleSheet() val interactiveBtn = cls( backgroundColor := "steelblue", color := "white", &.hover( backgroundColor := "darkblue" ), &.active( backgroundColor := "navy" ), &.hover.active( opacity := 0.9 ) ) } println(ButtonStyles.styleSheetText) // .ButtonStyles-interactiveBtn{ background-color: steelblue; color: white; } // .ButtonStyles-interactiveBtn:hover{ background-color: darkblue; } // .ButtonStyles-interactiveBtn:active{ background-color: navy; } // .ButtonStyles-interactiveBtn:hover:active{ opacity: 0.9; } ``` -------------------------------- ### Twirl Template with Scala and Scalatags Source: https://github.com/com-lihaoyi/scalatags/blob/master/scalatags/test/twirl/page.scala.html A Twirl template that accepts parameters and uses Scala for logic, including a loop to render dynamic content with Scalatags. ```Scala @(contentpara: String, first: String, titleString: String, firstParaString: String, paras: Seq[(Int, String)]) console.log(1) @titleString ============ @firstParaString [ Goooogle ](www.google.com)@for((i, color) <- paras){ @para(contentpara, i, color) } ``` -------------------------------- ### Add Scalatags to build.sbt Source: https://context7.com/com-lihaoyi/scalatags/llms.txt Include Scalatags in your project by adding the appropriate dependency to your build.sbt file for Scala JVM/Native or Scala.js. ```scala // Scala JVM / Scala Native libraryDependencies += "com.lihaoyi" %% "scalatags" % "0.13.1" ``` ```scala // Scala.js libraryDependencies += "com.lihaoyi" %%% "scalatags" % "0.13.1" ``` -------------------------------- ### Adding DOCTYPE Declaration with `doctype` Source: https://context7.com/com-lihaoyi/scalatags/llms.txt Add an HTML5 doctype to a full page using the `doctype` helper. ```Scala import scalatags.Text.all._ val fullPage = doctype("html")( html(lang := "en")( head( meta(charset := "UTF-8"), meta(name := "viewport", content := "width=device-width, initial-scale=1"), title("My App") ), body( h1("Welcome"), p("Content goes here") ) ) ) println(fullPage.render) // ... ``` -------------------------------- ### Handle Data and Aria Attributes Source: https://context7.com/com-lihaoyi/scalatags/llms.txt Use dot notation for `data.*` and `aria.*` attributes. Scalatags automatically converts these to hyphenated CSS names. Ensure correct import of `all._` for this functionality. ```scala import scalatags.Text.all._ val widget = div( // data-* attributes using dot notation id := "my-widget", data.columns := "3", data.index.number := "42", data.parent := "root", // aria-* attributes div( role := "tabpanel", aria.labelledby := "tab1", aria.expanded := "true" )("Tab panel content") ) println(widget.render) //
//
Tab panel content
//
``` -------------------------------- ### Group HTML Fragments with `frag` Source: https://context7.com/com-lihaoyi/scalatags/llms.txt Use `frag(...)` to group multiple `Frag` values into a single `Frag`. This simplifies passing collections of child nodes to parent elements. ```scala import scalatags.Text.all._ // Grouping child nodes val children: Frag = frag( h1("Hello"), p("First paragraph"), p("Second paragraph") ) val container = div(children) //

Hello

First paragraph

Second paragraph

``` -------------------------------- ### Cascading Stylesheets — CascadingStyleSheet Source: https://context7.com/com-lihaoyi/scalatags/llms.txt Opt in to cascading selectors by extending `CascadingStyleSheet`. Allows nesting tag selectors and class selectors inside a root class using `~` (descendant) and `>` (child) combinators. ```Scala import scalatags.stylesheet._ import scalatags.Text.all._ object NavStyles extends CascadingStyleSheet { initStyleSheet() val nav = cls( // Style for tags inside .nav a( color := "white", textDecoration.none ), // Style for :hover inside .nav a.hover( color := "lightblue", textDecoration.underline ) ) } println(NavStyles.styleSheetText) // .NavStyles-nav a{ color: white; text-decoration: none; } // .NavStyles-nav a:hover{ color: lightblue; text-decoration: underline; } val navHtml = nav(NavStyles.nav)( a(href := "/home")("Home"), a(href := "/about")("About") ) ``` -------------------------------- ### Bind Attributes with := Source: https://context7.com/com-lihaoyi/scalatags/llms.txt Attributes are bound using the `:=` operator. Standard attributes are available by default, and custom attributes can be created with `attr(name)`. Boolean attributes can be used standalone. ```scala import scalatags.Text.all._ val result = div( // Standard attributes p(onclick := "doSomething()", "Click me"), a(href := "https://example.com", target := "_blank")("Visit"), input(`type` := "text", placeholder := "Enter text", readonly), // Custom attribute div(attr("data-app-key") := "MY_KEY", attr("x-custom").empty), // Class and boolean attribute p(cls := "hero highlight", hidden)("Hidden paragraph") ) println(result.render) //
//

Click me

//
Visit // //
// //
``` -------------------------------- ### Integrate SVG with Scalatags Source: https://context7.com/com-lihaoyi/scalatags/llms.txt SVG tags and attributes are available in separate namespaces (`svgTags`, `svgAttrs`) and can be freely mixed with HTML. Import `svgTags._` and `svgAttrs._` for SVG-specific elements and attributes. ```scala import scalatags.Text.all._ import scalatags.Text.svgTags._ import scalatags.Text.svgAttrs._ val icon = div(cls := "icon")( svg( svgAttrs.width := "100", svgAttrs.height := "100", viewBox := "0 0 100 100" )( circle( cx := "50", cy := "50", r := "40", stroke := "#333", fill := "none", strokeWidth := "3" ), text(x := "50", y := "55", textAnchor := "middle")("Hi") ) ) println(icon.render) //
// // Hi
``` -------------------------------- ### Apply Scalatags Modifiers to Existing DOM Elements Source: https://context7.com/com-lihaoyi/scalatags/llms.txt Use the `applyTags` extension method on a `dom.Element` to imperatively apply Scalatags modifiers. This is specific to Scala.js projects. ```Scala import scalatags.JsDom.all._ import org.scalajs.dom val existingDiv = dom.document.getElementById("my-div") // Apply Scalatags modifiers to existing DOM elements existingDiv.applyTags( cls := "updated active", backgroundColor := "yellow", p("Dynamically inserted child") ) ``` -------------------------------- ### Auto-escaping Strings and Injecting Raw HTML Source: https://context7.com/com-lihaoyi/scalatags/llms.txt Explains that Scalatags automatically HTML-escapes string content in text nodes and attribute values for security. Use `raw(s: String)` to inject unescaped, trusted HTML. ```Scala import scalatags.Text.all._ val userInput = "" val trustedHtml = "Bold text with emphasis" val safe = div( // Automatically escaped — safe p("User said: ", userInput), // Raw unescaped HTML — use only for trusted content div(raw(trustedHtml)) ) println(safe.render) ``` -------------------------------- ### Group Modifiers with `modifier` Source: https://context7.com/com-lihaoyi/scalatags/llms.txt Use `modifier(...)` to group multiple `Modifier` values (attributes, styles, children) into a single `Modifier`. This is useful for defining reusable sets of attributes and styles. ```scala import scalatags.Text.all._ // Grouping modifiers (attributes + styles) def activeButtonMods: Modifier = modifier( cls := "btn btn-primary", backgroundColor := "blue", color := "white", disabled := false ) val btn = button(activeButtonMods)("Submit") // ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.