markdown_textarea.jinja 1.63 KB
Newer Older
Sli's avatar
Sli committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
<div>
	<textarea name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %}>
	{% if widget.value %}{{ widget.value }}{% endif %}</textarea>

	{# The simplemde script can be included twice, it's safe in the code #}
	<script src="{{ statics.js }}"> </script>
	<script type="text/javascript">
		var css = "{{ statics.css }}";

		// Only import the css once
		if (!document.head.innerHTML.includes(css)){
			document.head.innerHTML += '<link rel="stylesheet" href="' + css + '">';
		}

		// You can't get the csrf token from the template in a widget
		// We get it from a cookie as a workaround, see this link
		// https://docs.djangoproject.com/en/2.0/ref/csrf/#ajax
18 19 20 21 22 23 24 25 26 27 28
		function getCookie(cname) {
			var name = cname + "=";
			var decodedCookie = decodeURIComponent(document.cookie);
			var ca = decodedCookie.split(';');
			for(var i = 0; i <ca.length; i++) {
				var c = ca[i];
				while (c.charAt(0) == ' ') {
					c = c.substring(1);
				}
				if (c.indexOf(name) == 0) {
					return c.substring(name.length, c.length);
Sli's avatar
Sli committed
29 30
				}
			}
31
			return "";
Sli's avatar
Sli committed
32 33 34 35
		}

		// Custom markdown parser
		function customMarkdownParser(plainText, preview) {
Sli's avatar
Sli committed
36 37 38 39 40 41 42
			$.ajax({
				url: "{{ markdown_api_url }}",
				method: "POST",
				data: { text: plainText, csrfmiddlewaretoken: getCookie('csrftoken') },
			}).done(function (msg) {
				preview.innerHTML = msg;
			});
Sli's avatar
Sli committed
43 44 45 46 47 48 49 50
		}

		// Pretty markdown input
		var simplemde = new SimpleMDE({
			element: document.getElementById("{{ widget.attrs.id }}"),
			spellChecker: false,
			previewRender: function(plainText, preview){ // Async method
				customMarkdownParser(plainText, preview);
51
				return preview.innerHTML;
Sli's avatar
Sli committed
52 53 54 55 56
			}
		});

	</script>
</div>