Search code examples
jquery-pluginstwigbootstrap-datepickeruserfrosting

Why won't datepicker work in a twig in userfrosting?


Bit of a beginner here and this issue has been causing me a headache for over a day. I'm using userfrosting as a framework, with the usual twig files for the web pages.

I'm trying to include a datepicker (bootstrap-datepicker.js hasn't worked, neither is the current iteration using jquery-ui) in a form in a twig - but no matter what I do, I can't get it to work!

Here's the basic setup:

{% block head %}
    {{ parent() }}
    <script src="{{site.uri.js}}/jquery-1.11.2.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
    <script src="{{site.uri.js}}/custom.js" ></script>
{% endblock %}

{% block content %}
.... {{boring stuff missed out}}
<form class="form-inline" role="form">
.... {{boring stuff missed out}}
<div class="form-group row">
    <label for="datepicker" class="col-sm-3 form-control-label">Subject Date:</label>
    <div class="col-sm-6">
        <input type="date" class="form-control" id="datepicker" />
    </div>
</div>
.... {{boring stuff missed out}}
</form>
.... {{boring stuff missed out}}
{% endblock %}

{% block javascripts %}
<script type="text/javascript">
    $(document).ready(function() {
        $("#datepicker").datepicker();
    });
</script>
{% endblock %}

The box is on the page, you can type a date into it etc, but nothing appears when you click on it (there should be a calendar appearing.)

Anyone have any ideas? I'm at a total loss. I've tried various versions, locally and (as you can see, currently) on a CDN, but nothing works. I'm sure it's probably something basic as I'm not an experienced web dev or anything, but any advice or working examples would be gratefully received!


Solution

  • Uh! facepalm

    Well, after some digging and serious consideration of the inspector output (thanks CTRL-SHIFT-I!) it turns out to be a simple case of script loading order and multiple scripts being loaded.

    I didn't realise twig loads a whole bucketload of scripts on top of what I ask it to load in the template I was creating. Only after seeing the inspector output for the page did I see that I was trying to load two different versions of jQuery and my own custom script was being loaded out of order - I was loading them here:

    {% block head %}
      {{ parent() }}
      <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
      <script src="{{site.uri.js}}/custom.js" ></script>
    {% endblock %}
    

    that block should be reserved for stylesheets. Instead, I should be loading them here:

    {% block page_scripts %}
      <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
      <script src="{{site.uri.js}}/custom.js"></script>
    {% endblock %}
    

    ... so that they are loaded AFTER all the default Bootstrap and userfrosting scripts.