因爲我找不到關於這個問題的很多細節,我想我會回答我的問題。不幸的是,似乎瀏覽器不支持pyperclip,因此需要一個HTML + Javascript解決方法(在pyperclip中有意義)。首先,將Django Template var添加爲HTML屬性,然後使用Javascript來處理複製功能。下面是如何做到這一點的例子,提前抱歉,因爲stackoverflow給這個例子一些奇怪的格式。它還假定您使用email_list_clipboard的ID具有以下表單。我希望這可以幫助任何遇到類似問題的人!
實施例:
<html email-list="{{request.session.email_list}}">
<script>
$(document).ready(function() {
function copyTextToClipboard(text) {
var textArea = document.createElement("textarea");
// Place in top-left corner of screen regardless of scroll position.
textArea.style.position = 'fixed';
textArea.style.top = 0;
textArea.style.left = 0;
textArea.style.width = '2em';
textArea.style.height = '2em';
// We don't need padding, reducing the size if it does flash render.
textArea.style.padding = 0;
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';
textArea.style.background = 'transparent';
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
document.body.removeChild(textArea);
}
// set things up so my function will be called when field_three changes
$('#email_list_clipboard').click(function (click) {
event.preventDefault();
copyTextToClipboard(document.documentElement.getAttribute("email-list"));
});
</script>