base/src/sqwl/cms/package.scala
author Tomas Zeman <tomas@functionals.cz>
Tue, 29 Dec 2020 16:57:31 +0100
changeset 34 775d6da26993
parent 23 afcfbdeb3b88
permissions -rw-r--r--
Dynamic content rendering: current time tag.

/*
 * Copyright 2018-2020 Tomas Zeman <tomas@functionals.cz>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package sqwl

import java.nio.file.Path
import java.time.LocalDateTime

import scala.io.Source
import scala.util.{Failure, Success, Try}
import scalatags.Text.all._
import scalatags.text.Builder

package object cms {

  def readSourceFull(src: Source): Try[String] = {
    try {
      Success(src.getLines.mkString)
    } catch {
      case t: Throwable => Failure(t)
    } finally {
      src.close()
    }
  }

  def readFile(f: Path, enc: String = "UTF-8"): Try[String] =
    readSourceFull(Source.fromFile(f.toFile, enc))

  def readFile(f: String): String =
    readSourceFull(Source.fromFile(f, "UTF-8")) getOrElse ""

  def lnk(name: String, customUrl: String = ""): Frag = {
    val usedUrl = if (customUrl == "") name else customUrl
    a(name, href := usedUrl)
  }

  def time: Frag = new Frag {

    override def render: String = {
      println("time.render()")
      LocalDateTime.now().toString
    }

    override def applyTo(t: Builder): Unit = {
      println("time.applyTo()")
      t.addChild(render)
    }
  }
}