Class ServerMarkupContext

java.lang.Object
io.karatelabs.http.ServerMarkupContext
All Implemented Interfaces:
io.karatelabs.js.ObjectLike, io.karatelabs.js.SimpleObject, MarkupContext

public class ServerMarkupContext extends Object implements MarkupContext
Server-side context exposed to templates and API handlers. Implements MarkupContext for template compatibility and adds server-specific methods.

In templates and API handlers, access via the 'context' variable:

 <script ka:scope="global">
     context.log('Processing request');
     if (!session.user) {
         context.redirect('/signin');
     }
     var id = context.uuid();
 </script>
 
  • Field Details

    • FLASH_SESSION_KEY

      public static final String FLASH_SESSION_KEY
      Session key used to persist flash messages across redirects.
      See Also:
  • Constructor Details

  • Method Details

    • toVars

      public Map<String,Object> toVars()
      Build the standard variables map for template rendering. Includes global variables, request, response, context, and session.
    • getTemplateName

      public String getTemplateName()
      Description copied from interface: MarkupContext
      Returns the current template name (without leading slash).
      Specified by:
      getTemplateName in interface MarkupContext
    • getCallerTemplateName

      public String getCallerTemplateName()
      Description copied from interface: MarkupContext
      Returns the caller template name (for fragments/includes), or null if top-level.
      Specified by:
      getCallerTemplateName in interface MarkupContext
    • read

      public String read(String path)
      Description copied from interface: MarkupContext
      Read a resource as text.
      Specified by:
      read in interface MarkupContext
      Parameters:
      path - resource path (relative to template root or absolute)
      Returns:
      text content of the resource
    • readBytes

      public byte[] readBytes(String path)
      Description copied from interface: MarkupContext
      Read a resource as bytes.
      Specified by:
      readBytes in interface MarkupContext
      Parameters:
      path - resource path (relative to template root or absolute)
      Returns:
      byte array content of the resource
    • toJson

      public String toJson(Object obj)
      Description copied from interface: MarkupContext
      Serialize an object to JSON string.
      Specified by:
      toJson in interface MarkupContext
      Parameters:
      obj - object to serialize
      Returns:
      JSON string
    • fromJson

      public Object fromJson(String json)
      Description copied from interface: MarkupContext
      Parse a JSON string into an object (Map or List).
      Specified by:
      fromJson in interface MarkupContext
      Parameters:
      json - JSON string
      Returns:
      parsed object
    • getContextSession

      public Object getContextSession()
      Description copied from interface: MarkupContext
      Returns the session object if one exists, null otherwise. Used by template engine to sync session variable after context.init() is called. Default returns null (no session in plain templating mode).
      Specified by:
      getContextSession in interface MarkupContext
    • redirect

      public void redirect(String path)
      Set redirect path. This will cause a 302 redirect response.

      Throws a TemplateFlowSignal so the current template render or API handler evaluation is aborted cleanly (no further statements run, no downstream template errors logged). The signal is caught silently by the server request cycle; the actual redirect is driven by the redirectPath state set here.

    • log

      public void log(Object... args)
      Log a message. Messages are captured and can be retrieved via getLogMessages(). If a logHandler is configured in ServerConfig, it will be called. Otherwise, falls back to System.out.println.
    • uuid

      public String uuid()
      Generate a new UUID string.
    • init

      public void init()
      Initialize a new session. If sessions are not enabled in config, this is a no-op. Script and template bindings that reference session do so through a Supplier (see toVars() and ServerRequestCycle.createEngine()), so no callback is needed — the next access reads the live value.
    • close

      public void close()
      Close/invalidate the current session.
    • switchTemplate

      public void switchTemplate(String template)
      Switch to a different template for rendering.

      Throws a TemplateFlowSignal so the current template render is aborted cleanly (the original template is abandoned; the new one is rendered instead). The signal is caught silently by the server request cycle, which then renders switchTemplate in place of the original.

    • jsGet

      public Object jsGet(String key)
      Description copied from interface: MarkupContext
      Default implementation of jsGet that exposes context methods to JavaScript. Implementations can override to add more properties/methods.
      Specified by:
      jsGet in interface MarkupContext
      Specified by:
      jsGet in interface io.karatelabs.js.SimpleObject
    • getRequest

      public HttpRequest getRequest()
    • getResponse

      public HttpResponse getResponse()
    • getConfig

      public ServerConfig getConfig()
    • getSession

      public Session getSession()
    • setSession

      public void setSession(Session session)
    • setTemplateName

      public void setTemplateName(String templateName)
    • setCallerTemplateName

      public void setCallerTemplateName(String callerTemplateName)
    • setResourceResolver

      public void setResourceResolver(Function<String,io.karatelabs.common.Resource> resourceResolver)
    • getRedirectPath

      public String getRedirectPath()
    • hasRedirect

      public boolean hasRedirect()
    • isClosed

      public boolean isClosed()
    • wasExplicitlyClosed

      public boolean wasExplicitlyClosed()
      True iff close() was explicitly called this request — distinct from the broader isClosed() which also returns true when there was never a session to begin with. Used by ServerRequestHandler to decide whether to emit a session-cookie-clear Set-Cookie (defense-in-depth signout: server-side record is gone, so make sure the client's stale cookie is gone too).
    • isSwitched

      public boolean isSwitched()
    • getSwitchTemplate

      public String getSwitchTemplate()
    • getLogMessages

      public List<String> getLogMessages()
    • getFlash

      public Map<String,Object> getFlash()
    • loadFlashFromSession

      public void loadFlashFromSession()
      Load flash messages from session (if any) and clear them from session. Called at the start of request processing to retrieve messages set before a redirect.
    • persistFlashToSession

      public void persistFlashToSession()
      Persist current flash messages to session. Called before redirect so messages survive to the next request.
    • isAjax

      public boolean isAjax()
      Check if this is an AJAX/HTMX request.
    • getCsrfToken

      public CsrfProtection.CsrfToken getCsrfToken()
      Get the CSRF token object for templates. Returns a CsrfToken with token, headerName, and fieldName properties.
      Returns:
      CsrfToken object or null if CSRF is disabled or no session