Field Injection

SBCanvas.injectFields() substitutes field values into template strings without JavaScript DOM manipulation.

Basic Usage

const fields = SBCanvas.getFieldData();
// fields = { alert_title: "New Follower!", text_color: "#A78BFA" }

const html = SBCanvas.injectFields(
  '<h1 style="color: {{text_color}}">{{alert_title}}</h1>'
);
// '<h1 style="color: #A78BFA">New Follower!</h1>'

Context Parameter

The second argument controls escaping:
// HTML context (default) — escapes HTML entities
SBCanvas.injectFields('<p>{{message}}</p>', 'html');

// CSS context — escapes for stylesheet safety
SBCanvas.injectFields('color: {{text_color}}', 'css');

Targeting a Specific Widget

Pass a widget type or ID as the third argument:
const html = SBCanvas.injectFields('{{title}}', 'html', 'alert-box');

Listening for Dynamic Updates

When a field changes at runtime (via dashboard or setField()), the widget:field_change event fires:
SBCanvas.on('widget:field_change', ({ key, value, fieldData }) => {
  if (key === 'bg_color') {
    document.body.style.backgroundColor = value;
  }
});

Example: Dynamic Styling

SBCanvas.ready(() => {
  function applyStyles() {
    const f = SBCanvas.getFieldData();
    const el = document.getElementById('alert');
    el.style.color = f.text_color || '#ffffff';
    el.style.backgroundColor = f.bg_color || '#1a1a2e';
    el.style.fontSize = (f.font_size || 18) + 'px';
    el.style.fontFamily = f.font_family || 'Inter, sans-serif';
  }

  applyStyles();
  SBCanvas.on('widget:field_change', applyStyles);
});

API Reference

MethodReturnsDescription
injectFields(template, context?, typeOrId?)stringInterpolate field values into a template string