Class ServerMarkupContext
- All Implemented Interfaces:
io.karatelabs.js.ObjectLike,io.karatelabs.js.SimpleObject,ActionDispatchHost,MarkupContext
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 Summary
FieldsModifier and TypeFieldDescriptionstatic final StringSession key used to persist flash messages across redirects.Fields inherited from interface io.karatelabs.js.SimpleObject
logger, TO_STRING -
Constructor Summary
ConstructorsConstructorDescriptionServerMarkupContext(HttpRequest request, HttpResponse response, ServerConfig config) -
Method Summary
Modifier and TypeMethodDescriptionvoidclose()Close/invalidate the current session.Parse a JSON string into an object (Map or List).The (mutable) registry: action name → JS function.Returns the caller template name (for fragments/includes), or null if top-level.Returns the session object if one exists, null otherwise.Get the CSRF token object for templates.io.karatelabs.js.EnginegetFlash()Per-request engine-binding read with optional default.Companion accessor forMarkupContext.setMarkupScope(MarkupScope).Returns the current template name (without leading slash).booleanvoidinit()Initialize a new session.booleanWhether this request's action handler has already been dispatched.booleanisAjax()Check if this is an AJAX/HTMX request.booleanisClosed()booleanDefault implementation of jsGet that exposes context methods to JavaScript.voidLoad flash messages from session (if any) and clear them from session.voidLog a message.voidMark this request's action handler as dispatched.voidPersist current flash messages to session.Read a resource as text.byte[]Read a resource as bytes.voidSet redirect path.voidsetCallerTemplateName(String callerTemplateName) voidsetEagerDispatchHook(Consumer<String> hook) Hook installed by the template engine; invoked by the host'scontext.actionsview every time a key is set.voidsetEngine(io.karatelabs.js.Engine engine) Wired byServerRequestCycle.createEngine()sosetGlobal(String, Object)/getGlobal(String, Object)can route to the per-request JS engine bindings.voidPer-request escape hatch for setting JS-engine globals from inside aka:scope="local"block.voidsetMarkupScope(MarkupScope scope) Set the current-eval scope accessor.voidsetResourceResolver(Function<String, io.karatelabs.common.Resource> resourceResolver) voidsetSession(Session session) voidsetTemplateName(String templateName) voidswitchTemplate(String template) Switch to a different template for rendering.Serialize an object to JSON string.toVars()Build the standard variables map for template rendering.uuid()Generate a new UUID string.booleanTrue iffclose()was explicitly called this request — distinct from the broaderisClosed()which also returns true when there was never a session to begin with.Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface io.karatelabs.js.ObjectLike
getMember, getPrototype, isExtensible, isFrozen, isOwnProperty, isSealed, putMember, removeMember, setExtensible, setFrozen, setSealedMethods inherited from interface io.karatelabs.js.SimpleObject
getMember, jsKeys, jsToString, putMember, removeMember, toMap
-
Field Details
-
FLASH_SESSION_KEY
Session key used to persist flash messages across redirects.- See Also:
-
-
Constructor Details
-
ServerMarkupContext
-
-
Method Details
-
setMarkupScope
Description copied from interface:MarkupContextSet the current-eval scope accessor. Called byMarkupTemplateContextat engine-bind time socontext.getcan resolve names from_and the wrapped Thymeleaf scope. Default no-op for implementations that don't carry scope state.- Specified by:
setMarkupScopein interfaceMarkupContext
-
getMarkupScope
Description copied from interface:MarkupContextCompanion accessor forMarkupContext.setMarkupScope(MarkupScope). Default returns null; implementations override to surface the scope to thecontext.getdispatch path.- Specified by:
getMarkupScopein interfaceMarkupContext
-
toVars
Build the standard variables map for template rendering. Includes global variables, request, response, context, and session. -
getTemplateName
Description copied from interface:MarkupContextReturns the current template name (without leading slash).- Specified by:
getTemplateNamein interfaceMarkupContext
-
getCallerTemplateName
Description copied from interface:MarkupContextReturns the caller template name (for fragments/includes), or null if top-level.- Specified by:
getCallerTemplateNamein interfaceMarkupContext
-
read
Description copied from interface:MarkupContextRead a resource as text.- Specified by:
readin interfaceMarkupContext- Parameters:
path- resource path (relative to template root or absolute)- Returns:
- text content of the resource
-
readBytes
Description copied from interface:MarkupContextRead a resource as bytes.- Specified by:
readBytesin interfaceMarkupContext- Parameters:
path- resource path (relative to template root or absolute)- Returns:
- byte array content of the resource
-
toJson
Description copied from interface:MarkupContextSerialize an object to JSON string.- Specified by:
toJsonin interfaceMarkupContext- Parameters:
obj- object to serialize- Returns:
- JSON string
-
fromJson
Description copied from interface:MarkupContextParse a JSON string into an object (Map or List).- Specified by:
fromJsonin interfaceMarkupContext- Parameters:
json- JSON string- Returns:
- parsed object
-
getContextSession
Description copied from interface:MarkupContextReturns 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:
getContextSessionin interfaceMarkupContext
-
redirect
Set redirect path. This will cause a 302 redirect response.Throws a
TemplateFlowSignalso 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 theredirectPathstate set here. -
log
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
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 referencesessiondo so throughJsLazy(seetoVars()andServerRequestCycle.createEngine()), so no callback is needed — the next access reads the live value. -
close
public void close()Close/invalidate the current session. -
switchTemplate
Switch to a different template for rendering.Throws a
TemplateFlowSignalso 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 rendersswitchTemplatein place of the original. -
setGlobal
Per-request escape hatch for setting JS-engine globals from inside aka:scope="local"block. Routes toengine.put(name, value)so the value becomes a script-level global for the rest of the request, visible as a bare JS name in any subsequent eval (local or global) and viacontext.getGlobal(name).Distinct from
context.set(which writes to_, the per-template-render namespace). UsesetGlobalonly when a value needs to cross template renders within a request (e.g. content → shell).No-op when no engine is wired (non-server contexts).
-
getGlobal
Per-request engine-binding read with optional default. Symmetric reader forsetGlobal(String, Object). Returns the engine binding's value if set (non-null), else the default (or null when no default is given). Returns null when no engine is wired. -
jsGet
Description copied from interface:MarkupContextDefault implementation of jsGet that exposes context methods to JavaScript. Implementations can override to add more properties/methods.- Specified by:
jsGetin interfaceMarkupContext- Specified by:
jsGetin interfaceio.karatelabs.js.SimpleObject
-
getRequest
-
getResponse
-
getConfig
-
getSession
-
setSession
-
setTemplateName
-
setCallerTemplateName
-
setResourceResolver
-
setEngine
public void setEngine(io.karatelabs.js.Engine engine) Wired byServerRequestCycle.createEngine()sosetGlobal(String, Object)/getGlobal(String, Object)can route to the per-request JS engine bindings. -
getEngine
public io.karatelabs.js.Engine getEngine() -
getRedirectPath
-
hasRedirect
public boolean hasRedirect() -
isClosed
public boolean isClosed() -
wasExplicitlyClosed
public boolean wasExplicitlyClosed()True iffclose()was explicitly called this request — distinct from the broaderisClosed()which also returns true when there was never a session to begin with. Used byServerRequestHandlerto decide whether to emit a session-cookie-clearSet-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
-
getLogMessages
-
getFlash
-
getActions
Description copied from interface:ActionDispatchHostThe (mutable) registry: action name → JS function. JS code populates this viacontext.actions['name'] = function(form){...}.- Specified by:
getActionsin interfaceActionDispatchHost
-
isActionDispatched
public boolean isActionDispatched()Description copied from interface:ActionDispatchHostWhether this request's action handler has already been dispatched. The framework calls this before each potential dispatch attempt so the handler runs at most once per request.- Specified by:
isActionDispatchedin interfaceActionDispatchHost
-
markActionDispatched
public void markActionDispatched()Description copied from interface:ActionDispatchHostMark this request's action handler as dispatched. Called by the template engine after a successful dispatch.- Specified by:
markActionDispatchedin interfaceActionDispatchHost
-
setEagerDispatchHook
Description copied from interface:ActionDispatchHostHook installed by the template engine; invoked by the host'scontext.actionsview every time a key is set. Lets the engine dispatch the matching handler eagerly — i.e. as soon as it is registered — so any state reads later in the same script block observe post-mutation data. No-op default keeps non-server (plain templating) contexts simple.- Specified by:
setEagerDispatchHookin interfaceActionDispatchHost
-
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
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
-