Skip to content
Advertisement

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,})

Advertisement

Answer

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 document.text.select() and document.execCommand('copy').

Perhaps the following example will suffice:

in html code

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

javascript:

{% block scripts %}
<script>
  function CopyText() {
  var text = document.getElementById('yourtext')
  text.select();
  document.execCommand('copy')
}
</script>
{% 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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement