Output Url of image into Javascript

I created a engineer field field that allows a user to select an image and a colour on the home.yml blueprint. I would like this selection to be able to be used in Javascript so I’m going to output an array in the footer snippet. How do I output the uploaded images URL?

JS

<script type="text/javascript">
	var colours = [
		<?php $colours = page('home')->colours() ?>
		<?php foreach($colours->yaml() as $colour):?>
			{bg: '<?php echo $colour['bg'] ?>', flag:'<?php echo $colour['image']->url() ?>'},
		<?php endforeach ?>
	];
</script>

Blueprint

  colours:
    label: Background Setup
    type: engineer
    fields:
      image:
        label: Selected Image
        type: image
        width: 1/2
      bg:
        label: Background Colour
        help: Type in HEX code
        type: color
        width: 1/2

With structure():

    <script type="text/javascript">
    	var colours = [
    		<?php $colours = page('home')->colours() ?>
    		<?php foreach($colours->structure() as $colour):?>
                 <?php ($image = $colour->image()->toFile())? $url = $image->url(): $url=''; ?>
    			{bg: '<?php echo $colour->bg() ?>', flag:'<?php echo $url ?>'},
    		<?php endforeach ?>
    	];
    </script>

With yaml():

<script type="text/javascript">
	var colours = [
		<?php $colours = page('home')->colours() ?>
		<?php foreach($colours->yaml() as $colour):?>
                  <?php ($image = $page->image($colour['image']))? $url = $image->url(): $url=''; ?>
			{bg: '<?php echo $colour['bg'] ?>', flag:'<?php echo $url ?>'},
		<?php endforeach ?>
	];
</script>

Thank you, that’s exactly what I was trying to do.

What does $url=''; do?

It gives you an empty string in case the image does not exist. If you call the url() method without checking if the image exists, you get an error. No image = no url.

1 Like