I'm using the flot module to create some graphs in Drupal. Generally, it is working pretty well. However, I have come across an issue which is more general.
I am defining a settings array, which works for most things, but some flot settings allow for anonymous functions:
xaxis: {
transform: function (v) { return Math.log(v); },
inverseTransform: function (v) { return Math.exp(v); }
}
How could I encode this in PHP so that it will be output correctly? The flot module uses drupal_to_js()
, and I can't put it outside of quotes as PHP will try to interpret it. If I put it inside quotes it will be treated as a string.
From my googleing it looks like json_encode()
also doesn't support this.
A little more explanation: drupal_to_js()
takes a PHP structure and transposes it to JavaScript.
$top = array(
'a_string' => 'A string will convert fine',
'a_number' => 123 // as will a number,
'an_array' => array('a' => 'nested arrays work fine too'),
);
This will be transposed to something like
[ a_string: 'A string will convert fine', a_number: 123 ...
I want to transpose a function; the following code will give me the string 'function (v) { return Math.log(v); }'
.
$top = array(
'a_string' => 'function (v) { return Math.log(v); }',
);
The following code will give me a PHP parse error (as it should be).
$top = array(
'a_string' => function (v) { return Math.log(v); },
);
I want the text in the string to be used as a JavaScript literal, but I don't think it can be done.
Has anyone found a good way round this? I could output some raw JavaScript, but then I will lose a lot of functionality.
drupal_to_js()
?SyntaxError: JSON Parse error: Unexpected identifier "function"
.