Skip to content

how to copy variable to [clipboard] in django template

How do I copy a variable from inside the html page of Django templates?

render(request, 'doc.html', {'stack': stack, 'text':text,})


Your question may not seem clear enough to describe what you want or describe your problem, but some of my guesses for the solution are that you need to use js code in your template, specifically and document.execCommand('copy').

Perhaps the following example will suffice:

in html code

     <button style="background:green; text-align:center;" onclick="CopyText()">Copy Text</button>
     <input style="text-align:center;" type="text" value="{{text}}"id="yourtext">


{% block scripts %}
  function CopyText() {
  var text = document.getElementById('yourtext');
{% endblock scripts %}

In the example shown above, we used the value of the variable that you send to the template as a default value in the text tag, and then we specify the text through the tag’s ID yourtext, and then execute the copy command. It may not seem perfect but it is enough to solve your problem.