Ace editor doesn't format the data inside the editor div

冷暖自知 提交于 2019-12-06 03:47:11

Ace doesn't support formatting the code, you can either use beautify.js or browsers built-in json formatter

var val = editor.session.getValue()
var o = JSON.parse(val) // may throw if json is malformed
val = JSON.stringify(o, null, 4) // 4 is the indent size
editor.session.setValue(val)

I used beautify and used js_beautify function and work done.

Mr. Polywhirl

As a user mentioned, you should go with beautify.js.

I tried including the Ace Beautifier plugin, but the formatting was completely off.

// https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.6/ext-beautify.js
var beautify = ace.require('ace/ext/beautify');

beautify.beautify(editor.getSession());

Here is an example of hooking JS Beautifier into your existing Ace Editor.

// Variables
var editor = ace.edit('editor');
var txtAra = document.querySelector('textarea[name="editor"]');
var jsbOpts = {
  indent_size : 2
};

// Setup
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/json");
syncEditor();

// Main Logic
setTimeout(formatCode, 1000); // Format sample JSON after 1 second.

// Functions
function syncEditor() {
  editor.getSession().setValue(txtAra.value);
}
function commitChanges() {
  txtAra.value = editor.getSession().getValue();
}
function formatCode() {
  var session = editor.getSession();
  session.setValue(js_beautify(session.getValue(), jsbOpts));
}
.title {
  font-size: 1.67em;
  font-weight: bold;
  text-align: center;
}
#editor {
  height: 75vh;
  width: 100%;
}
textarea[name="editor"] {
  display: none;
}

.as-console-wrapper {
  display: none !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.6/ace.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.6.8/beautify.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css" rel="stylesheet"/>
<div>
  <div class="title">Ace Editor - JSON Format</div>
  <textarea name="editor">{"glossary": {"title": "example glossary","GlossDiv": {"title": "S","GlossList": {"GlossEntry": {"ID": "SGML","SortAs": "SGML","GlossTerm": "Standard Generalized Markup Language","Acronym": "SGML","Abbrev": "ISO 8879:1986","GlossDef": {"para": "A meta-markup language, used to create markup languages such as DocBook.","GlossSeeAlso": ["GML", "XML"]},"GlossSee": "markup"}}}}}</textarea>
  <div id="editor"></div>
</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!