Skip to content

Commit

Permalink
new handlebars helper for custom components: app_config
Browse files Browse the repository at this point in the history
  • Loading branch information
lovasoa committed Jun 17, 2024
1 parent 8aa3f29 commit 721ced6
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
- allow using `FALSE as tile_source` to completely remove the base map. This makes the map component useful to display even non-geographical geometric data.
- Fix a bug that occured when no `database_url` was provided in the configuration file. SQLPage would generate an incorrect default SQLite database URL.
- Add a new `background_color` attribute to the [card](https://sql.ophir.dev/documentation.sql?component=card#component) component to set the background color of the card.
- new handlebars helper for [custom components](https://sql.ophir.dev/custom_components.sql): `{{app_config 'property'}}` to access the configuration object from the handlebars template.

## 0.23.0 (2024-06-09)

Expand Down
2 changes: 2 additions & 0 deletions examples/official-site/custom_components.sql
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,8 @@ and SQLPage adds a few more:
- if the argument is a string containing a valid json list, returns the parsed list,
- otherwise returns a list containing only the argument
- `array_contains`: returns true if a list contains a value
- `static_path`: returns the path to one of the static files bundled with SQLPage. Accepts arguments like `sqlpage.js`, `sqlpage.css`, `apexcharts.js`, etc.
- `app_config`: returns the value of a configuration parameter from sqlpage''s configuration file, such as `max_uploaded_file_size`, `site_prefix`, etc.
- `icon_img`: generate an svg icon from a *tabler* icon name
- `markdown`: renders markdown text
- `each_row`: iterates over the rows of a query result
Expand Down
4 changes: 2 additions & 2 deletions src/app_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use anyhow::Context;
use config::Config;
use percent_encoding::AsciiSet;
use serde::de::Error;
use serde::{Deserialize, Deserializer};
use serde::{Deserialize, Deserializer, Serialize};
use std::net::{SocketAddr, ToSocketAddrs};
use std::path::{Path, PathBuf};

Expand Down Expand Up @@ -280,7 +280,7 @@ fn default_https_acme_directory_url() -> String {
"https://acme-v02.api.letsencrypt.org/directory".to_string()
}

#[derive(Debug, Deserialize, PartialEq, Clone, Copy, Eq, Default)]
#[derive(Debug, Deserialize, Serialize, PartialEq, Clone, Copy, Eq, Default)]
#[serde(rename_all = "lowercase")]
pub enum DevOrProd {
#[default]
Expand Down
33 changes: 33 additions & 0 deletions src/template_helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ use handlebars::{
};
use serde_json::Value as JsonValue;

/// Simple static json helper
type H0 = fn() -> JsonValue;
/// Simple json to json helper
type H = fn(&JsonValue) -> JsonValue;
/// Simple json to json helper with error handling
Expand Down Expand Up @@ -41,6 +43,7 @@ pub fn register_all_helpers(h: &mut Handlebars<'_>, config: &AppConfig) {

// static_path helper: generate a path to a static file. Replaces sqpage.js by sqlpage.<hash>.js
register_helper(h, "static_path", StaticPathHelper(site_prefix.clone()));
register_helper(h, "app_config", AppConfigHelper(config.clone()));

// icon helper: generate an image with the specified icon
h.register_helper("icon_img", Box::new(IconImgHelper(site_prefix)));
Expand Down Expand Up @@ -154,6 +157,27 @@ impl CanHelp for StaticPathHelper {
}
}

/// Generate the full path to a builtin sqlpage asset. Struct Param is the site prefix
struct AppConfigHelper(AppConfig);

impl CanHelp for AppConfigHelper {
fn call(&self, args: &[PathAndJson]) -> Result<JsonValue, String> {
let static_file = match args {
[v] => v.value(),
_ => return Err("expected one argument".to_string()),
};
let name = static_file
.as_str()
.ok_or_else(|| format!("app_config: not a string: {static_file}"))?;
match name {
"max_uploaded_file_size" => Ok(JsonValue::Number(self.0.max_uploaded_file_size.into())),
"environment" => serde_json::to_value(self.0.environment).map_err(|e| e.to_string()),
"site_prefix" => Ok(self.0.site_prefix.clone().into()),
other => Err(format!("unknown app config property: {other:?}")),
}
}
}

/// Generate an image with the specified icon. Struct Param is the site prefix
struct IconImgHelper(String);
impl HelperDef for IconImgHelper {
Expand Down Expand Up @@ -333,6 +357,15 @@ trait CanHelp: Send + Sync + 'static {
fn call(&self, v: &[PathAndJson]) -> Result<JsonValue, String>;
}

impl CanHelp for H0 {
fn call(&self, args: &[PathAndJson]) -> Result<JsonValue, String> {
match args {
[] => Ok(self()),
_ => Err("expected no arguments".to_string()),
}
}
}

impl CanHelp for H {
fn call(&self, args: &[PathAndJson]) -> Result<JsonValue, String> {
match args {
Expand Down

0 comments on commit 721ced6

Please sign in to comment.