Adding scripts to the head and footer

Friends, help us with advice.

Adding “HighCharts” to the page requires loading scripts to the head of the page and to the footer.
Charts are only displayed on certain pages.
It is undesirable to make separate templates for them.
Added fields (addscripthead and addscriptfooter) to the blueprint file with the path to the scripts.
How to code adding scripts correctly?

Now I’m doing this.
/snippets/head

<?php if($page->uid() == 'pagechart'): ?>
<?php echo js([
'assets/js/chart/highcharts.js',
'assets/js/chart/sankey.js',
'assets/js/chart/organization.js',
]) ?>
<?php endif ?>

/snippets/footer

<?php if ($page->uid() == 'pagechart'): ?>
  <?php echo js('assets/js/chart/chart.js') ?>
<?php endif ?>

It’s hardcoded.

How do I check for the existence of a field? And if it is not empty, insert scripts.
Sketch.
I’ll add more details.
Thanks for the help.

There are two field methods you can use:

$field->exists();
$field->isNotEmpty(); // or `isEmpty()`
1 Like

Wow.
Thanks @pixelijn.
Now I will try to write the code.

Friends, please tell me.
Is the code logic correct?

<?php if(in_array($page->uid(),array('page1','page2'))): ?>
	<?php echo js('assets/js/chart/highcharts.js') ?>
<?php endif ?>

<?php if ($page->uid() == 'page1'): ?>
	<?php echo js([
	'assets/js/chart/sankey.js',
	'assets/js/chart/organization.js',
	]) ?>
<?php endif ?>

Everything works, but is this code construct pretty?
On “page1” three scripts are connected, on “page2” only one of these three is connected.

“Don’t throw Slippers”. All were once students. :upside_down_face:

Yes, that’s perfectly ok.

1 Like

Just on a side note: If the uid of the page is changed, the scripts won’t be loaded anymore. I don’t know if it would be a solution to set changeSlug: false in your blueprint, because that would affect all page that use this template.

1 Like

Thanks to @texnixe
Links do not change. The content of the page is sometimes edited.
New pages are added to the site.
But the links to the pages have not changed since 2012.
Preschool educational institution website.
The topic is still open, because I have not yet decided how to do it right.
For the sake of two pages, process the condition every time the template is accessed. Not camilfo.
While I think.

I don’t think these if statement are very expensive. What you can do to clean up a bit, is move the code into a snippet, then you have only one if statement in the header/footer

<?php if(in_array($page->uid(),array('page1','page2'))): ?>
	<?php snippet('chartscripts') ?>
<?php endif ?>

In snippet:

<?php echo js('assets/js/chart/highcharts.js') ?>
<?php if ($page->uid() == 'page1'): ?>
	<?php echo js([
	'assets/js/chart/sankey.js',
	'assets/js/chart/organization.js',
	]) ?>
<?php endif ?>
1 Like

Wow.
Yes.
Thanks.
So I will.