Django进阶教程--自定义wiget markdown编辑器
django提供widget机制可以将重复使用的html封装起来,实现html代码的复用,同时内置了很多基础widget,方便我们使用。但是内置的widget并不能满足我们个性化开发需求,这时候就需要自定义widget,本节借着实现一个markdown编辑器来向大家讲解如何实现一个自定义组件。
markdown js插件editor.md介绍
我们的markdown编辑器是基于开源的js插件editor.md( http://pandao.github.io/editor.md/)实现的,先来简单了解下editor.md的使用。
首先从官网下载代码,我们只需要以下几个文件夹
css
fonts
images
lib
plugins
然后新建js文件夹,将editor.min.js、jquery.min.js复制到js文件夹下。
在该目录下新建test.html,代码如下:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8" />
<title>Simple example - Editor.md examples</title>
<link rel="stylesheet" href="css/editormd.css" />
<link rel="shortcut icon" href="https://pandao.github.io/editor.md/favicon.ico" type="image/x-icon" />
</head>
<body>
<div id="layout">
<header>
<h1>Simple example</h1>
</header>
<div id="test-editormd">
<textarea style="display:none;">
</textarea>
</div>
</div>
<script src="js/jquery.min.js"></script>
<script src="js/editormd.min.js"></script>
<script type="text/javascript">
var testEditor;
$(function() {
testEditor = editormd("test-editormd", {
width : "90%",
height : 640,
syncScrolling : "single",
path : "lib/",
/**上传图片相关配置如下*/
imageUpload : true,
imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
imageUploadURL : "/smart-api/upload/editormdPic/",//注意你后端的上传图片服务地址
});
/*
// or
testEditor = editormd({
id : "test-editormd",
width : "90%",
height : 640,
path : "lib/"
});
*/
});
</script>
</body>
</html>
在浏览器中打开test.html,就可以看到editor.md编辑器
html代码比较简单,大家应该可以看懂,就是在div下有一个textarea,然后在js代码新建editormd组件,注意里面path属性为lib文件夹路径。
自定义widget
django中widget代码如下
class Widget(six.with_metaclass(MediaDefiningClass)):
needs_multipart_form = False # Determines does this widget need multipart form
is_localized = False
is_required = False
def __init__(self, attrs=None):
if attrs is not None:
self.attrs = attrs.copy()
else:
self.attrs = {}
def __deepcopy__(self, memo):
obj = copy.copy(self)
obj.attrs = self.attrs.copy()
memo[id(self)] = obj
return obj
@property
def is_hidden(self):
return self.input_type == 'hidden' if hasattr(self, 'input_type') else False
@is_hidden.setter
def is_hidden(self, *args):
warnings.warn(
"`is_hidden` property is now read-only (and checks `input_type`). "
"Please update your code.",
RemovedInDjango18Warning, stacklevel=2
)
def subwidgets(self, name, value, attrs=None, choices=()):
"""
Yields all "subwidgets" of this widget. Used only by RadioSelect to
allow template access to individual <input type="radio"> buttons.
Arguments are the same as for render().
"""
yield SubWidget(self, name, value, attrs, choices)
def render(self, name, value, attrs=None):
"""
Returns this Widget rendered as HTML, as a Unicode string.
The 'value' given is not guaranteed to be valid input, so subclass
implementations should program defensively.
"""
raise NotImplementedError('subclasses of Widget must provide a render() method')
def build_attrs(self, extra_attrs=None, **kwargs):
"Helper function for building an attribute dictionary."
attrs = dict(self.attrs, **kwargs)
if extra_attrs:
attrs.update(extra_attrs)
return attrs
def value_from_datadict(self, data, files, name):
"""
Given a dictionary of data and this widget's name, returns the value
of this widget. Returns None if it's not provided.
"""
return data.get(name, None)
def id_for_label(self, id_):
"""
Returns the HTML ID attribute of this Widget for use by a <label>,
given the ID of the field. Returns None if no ID is available.
This hook is necessary because some widgets have multiple HTML
elements and, thus, multiple IDs. In that case, this method should
return an ID value that corresponds to the first ID in the widget's
tags.
"""
return id_
其中有render方法为关键方法,用于渲染html代码,id_for_label方法用于生成id,主要用于表单提交,还有一个属性media用于添加css和js文件,自定义组件主要重载render和media方法来。
markdown编辑器主要用来替代系统的textfield,所以我们通过继承forms.Textarea来实现自定义组件,具体代码如下
class MarkdownWidget(forms.Textarea):
def __init__(self, *args, **kwargs):
self.template = kwargs.pop(
"template", markdown_settings.MARKDOWN_WIDGET_TEMPLATE)
self.lib=markdown_settings.STATIC_URL+"markdown/lib/"
self.width=kwargs.pop("width","100%")
self.height = kwargs.pop("height", "540")
self.syncScrolling=kwargs.pop("syncScrolling","single")
self.saveHTMLToTextarea=kwargs.pop("saveHTMLToTextarea",True)
self.emoji=kwargs.pop("emoji",True)
self.taskList=kwargs.pop("taskList",True)
self.tocm=kwargs.pop("tocm",True)
self.tex=kwargs.pop("tex",True)
self.flowChart=kwargs.pop("flowChart",True)
self.sequenceDiagram=kwargs.pop("sequenceDiagram",True)
self.codeFold=kwargs.pop("codeFold",True)
self.imageUpload=kwargs.pop("imageUpload",True)
self.imageFormats=kwargs.pop("imageFormats",markdown_settings.MARKDOWN_IMAGE_FORMATS)
self.imageUploadURL=kwargs.pop("imageUploadURL",markdown_settings.MARKDOWN_UP_IMAGE_URL)
self.theme=kwargs.pop("theme", "light")
self.previewTheme=kwargs.pop("previewTheme","light")
self.editorTheme=kwargs.pop("editorTheme", "paraiso-light")
super(MarkdownWidget, self).__init__(*args, **kwargs)
def _media(self):
return forms.Media(
css={
"all": (compatible_staticpath("markdown/css/editormd.css"),)
},
js=(
compatible_staticpath("markdown/js/jquery.min.js"),
compatible_staticpath("markdown/js/editormd.min.js"),
))
media = property(_media)
def render(self, name, value, attrs=None):
if value is None:
value = ""
if VERSION < (1, 11):
final_attrs = self.build_attrs(attrs, name=name)
else:
final_attrs = self.build_attrs(attrs, {'name': name})
if "class" not in final_attrs:
final_attrs["class"] = ""
final_attrs["class"] += " wmd-input"
template = loader.get_template(self.template)
# imageFormats_str=','.join('"'+i+'"' for i in self.imageFormats)
# imageFormats_str='['+imageFormats_str+']'
markdown_conf={
'width':self.width,
'height':self.height,
'syncScrolling': self.syncScrolling,
'saveHTMLToTextarea' : self.saveHTMLToTextarea,
'emoji':self.emoji,
'taskList':self.taskList,
'tocm':self.tocm,
'tex':self.tex,
'flowChart':self.flowChart,
'sequenceDiagram':self.sequenceDiagram,
'codeFold':self.codeFold,
'imageUpload':self.imageUpload,
'imageFormats':self.imageFormats,
'imageUploadURL':self.imageUploadURL,
'theme': self.theme,
'previewTheme': self.previewTheme,
'editorTheme':self.editorTheme,
}
context = {
"attrs": flatatt(final_attrs),
"body": conditional_escape(force_unicode(value)),
"id": final_attrs["id"],
"marklib":self.lib,
"markdownconf":markdown_conf,
}
context = Context(context) if VERSION < (1, 9) else context
return template.render(context)
我们通过media加载所需的js/css文件,然后重载render方法渲染template文件并返回,在render方法中我们需要通过父类的buildattrs来构建html组件的属性,value为组件初始值,对于本组件来说就是默认文本,然后我们还需要传入editor.md的属性,模板代码如下:
<div class="wmd-wrapper" id="{{ id }}-wmd-wrapper">
<textarea {{ attrs|safe }}>{{ body }}</textarea>
</div>
<script type="text/javascript">
var markdownEditor;
$(function() {
markdownEditor = editormd("{{ id }}-wmd-wrapper", {
width : "{{markdownconf.width}}",
height : "{{markdownconf.height}}",
theme :"{{markdownconf.theme}}",
previewTheme : "{{markdownconf.previewTheme}}",
editorTheme : "{{markdownconf.editorTheme}}",
syncScrolling : "{{markdownconf.syncScrolling}}",
saveHTMLToTextarea : {{markdownconf.saveHTMLToTextarea|lower}},
emoji: {{markdownconf.emoji|lower}},
taskList: {{markdownconf.taskList|lower}},
tocm: {{markdownconf.tocm|lower}},
tex: {{markdownconf.tex|lower}},
flowChart: {{markdownconf.flowChart|lower}},
sequenceDiagram: {{markdownconf.sequenceDiagram|lower}},
codeFold: {{markdownconf.codeFold|lower}},
path : "{{marklib}}",
{%if markdownconf.imageUpload%}
imageUpload : {{markdownconf.imageUpload|lower}},
imageFormats :{{markdownconf.imageFormats|safe}},
imageUploadURL : "{{markdownconf.imageUploadURL|safe}}",
{%endif%}
});
});
</script>
和上面代码类似,不做过多讲解。
最终实现效果如下:
我已将组件封装成一个app,并已将代码上传到github上(https://github.com/feiyin0719/django-markdown-editor),觉得不错的还请大家给个star,在此先多谢大家啦