2
votes

I'm trying something different for a SilverStripe project: I need to find a way to take fields in the CMS and put them into JavaScript variables for use in a JavaScript file.

For starters, I have a Header CMS field in Page.php:

private static $db = array(
    'Header' => 'HTMLText'
);

public function getCMSFields() {
    $fields = parent::getCMSFields();

    $fields->addFieldToTab('Root.Main', new HTMLEditorField('Header', 'Header'));

    return $fields;
}

And I want to reference that field inside a JavaScript file as a variable:

       {
            id: 'Text-Intro',
            type: 'text',
            rect: ['251px', '250px','641px','71px','auto', 'auto'],
            text: [Header variable needs to go here],
            align: "left",
            font: ['Arial, Helvetica, sans-serif', 25, "rgba(0,0,0,1.00)", "500", "none", "normal"]
        },

I tried making use of the Requirements::javascriptTemplate() function but the variable isn't recognized inside the detail-page_edge.js file:

public function init() {
    parent::init();

    Requirements::javascriptTemplate('/themes/simple/javascript/detail-page_edge.js', array(
        'Header' => $this->Header
    ));
}

Something must be missing, or maybe this is just outdated? I've never tried this in SilverStripe before. I don't have much of a choice, though, considering how this project is setup.

1

1 Answers

4
votes

You can use SilverStripe template syntax for simple variable-replacement. So your JS file should read:

// ... plain JS code
text: '$Header',
// ... more JS code

Please note, that you can't use more complex template syntax, such as <% loop … %> or <% if … %>, as javascriptTemplate will just do variable substitution.

If you need the full template features, you could render a .ss template file to string and output it with Requirements::customScript. I don't think you should ever do that though… even processing JS files through javascriptTemplate seems off. I'd rather use HTML data-attributes in your regular markup (eg. .ss templates) and write the JavaScript in a way that it'll grab the required attributes and builds upon the markup.

Also: Make sure your path to the file is correct. Instead of writing the absolute path:

'/themes/simple/javascript/detail-page_edge.js'

I suggest you use the following:

$this->ThemeDir() . '/javascript/detail-page_edge.js'