Skip to content

Instantly share code, notes, and snippets.

@myselfhimself
Last active April 11, 2023 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myselfhimself/15cd935c52b7c4ffa03d8329c7934a72 to your computer and use it in GitHub Desktop.
Save myselfhimself/15cd935c52b7c4ffa03d8329c7934a72 to your computer and use it in GitHub Desktop.
Implementing clipboard-js in Symfony / Twig with Webpack Encore

ClipboardJS allows for Flash-less copying into a device's clipboard.

Here are hints on implementing it in a Symfony setup with Wepback Encore already in place.

In the Symfony project's root directory run:

npm install clipboard --save

In /webpack.config.js, add this line:

// ...
/** SomeSite assets */
encoreFactory('someSite')
    //.addEntry('someEntry', './assets/someSite/js/index.js')
    .copyFiles([
        // ...
        { from: './node_modules/jquery/dist', pattern: /jquery.min.js/, to: 'jquery.min.js' },
        // ...
    ])
;

To see effects live, you may run yarn watch or npm run watch (see more)

Here is an example implementation for your template file:


{% block content %}
  <div class="row">
    <div class="col-md-12">
      <h4>Time for breakfast in bed</h4>
    </div>
    <div class="col-md-12">
      <p>
        Keep calm and...
      </p>
      <!-- Target for clipboard copying -->

      {% set breakfastUrl = 'https://www.bbcgoodfood.com/recipes/collection/breakfast-recipes' %}
      <input class="col-md-5" id="breakfast-url" value="{{ breakfastUrl }}" />

      <!-- Trigger for clipboard copying -->
      <button class="btn" id="copy-button" data-clipboard-target="#breakfast-url" title="Copy to clipboard"><i class="mdi mdi-clipboard-text" alt="Copy to clipboard"></i></button>
      <a class="btn" href="{{ breakfast-url }}" target="_blank" title="Open breakfast recipe ideas."><i class="mdi mdi-bed" alt="Bed icon"></i></a>
    </div>
  </div>
{% endblock %}

{% block js %}
  <script src="{{ asset('build/someSite/clipboard.min.js') }}"></script>
  <script>
    new ClipboardJS('#copy-button')
  </script>
{% endblock %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment