1

I want to put a few simple text fields into Craft CP and then be able to retrieve them with JavaScript.

What is the best way to structure this in Craft? I'd like to be able to create/edit an "entry" and then do something like this:

<script type="text/javascript">
    var homepageContent = {{ craft.entries.homepageContent }};
    console.log('details: ', homepageContent);
</script>

The homepage content entry in Craft needs to have ~2-3 fields attached to it.

I created the 3 fields that I think I will need to be editable on the homepage. Now I'm unsure how to get these tied to be able to enter an "entry" into something like a Homepage Content group?

2

One way to go about this is to use the JSON Expand plugin from Familiar Studio:

https://github.com/familiar-studio/craft-json-expand

It's pretty easy to use:

{% set hpContent = craft.entries.section('homepageContent').find() %}

Then you can just grab the data you need from the json object like:

<script type="text/javascript">
    var homepageContent = hpContent|json_expand|raw }};
    console.log({{ hpContent|json_expand|raw }});
</script>

One caveat I've found though is that content in Rich Text editors doesn't output. If you're just using simple text fields, then you should be fine. If you do need something Rich Text-like, you could use Craft's |markdown filter on data from a simple text field.

1

This is how I did it:

<script type="text/javascript">
     var bpDetails = {
         buttonText: '{{ siteOptions.buttonText }}',
         descriptionText: '{{ siteOptions.descriptionText }}'
     };
</script>

I was then able to access this variable in my AngularJS portion and check

if(bpDetails)
  vm.bpDetails = bpDetails; 

That way I was able to use the craft content stored into a JS object to display/manipulate in the view.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.