There are countless approaches to achieving this, and here's how I tackled it using the Smarty Template Engine. However, this method should be adaptable to plain HTML as well.
To begin with, consider the following sample HTML snippet from my "dog_fleas.tpl" template file:
<script type="text/javascript" src="/js/ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="/js/admin/mycms.js"></script>
<div>
<div id="flea-blurb" tpl="/templates/dog_fleas.tpl" contenteditable="true">
<h1>My Dog Has Fleas</h1>
<p>This text is editable via the CMS!</p>
</div>
<p>This text is not editable</p>
</div>
Below is the JavaScript code (mycms.js) responsible for managing the inline editing functionality:
$(document).ready(function() {
CKEDITOR.disableAutoInline = true;
$("div[contenteditable='true']" ).each(function( index ) {
var content_id = $(this).attr('id');
var tpl = $(this).attr('tpl');
CKEDITOR.inline( content_id, {
on: {
blur: function( event ) {
var data = event.editor.getData();
var request = jQuery.ajax({
url: "/admin/cms-pages/inline-update",
type: "POST",
data: {
content : data,
content_id : content_id,
tpl : tpl
},
dataType: "html"
});
}
}
} );
});
});
The provided script carries out a few key tasks:
- It converts any div element with the attribute contenteditable set to "true" into an editable region.
- Upon editing the content (on blur), the ID of the edited element, template filename, and modified content are transmitted to the server via an ajax call.
In my scenario, the tpl attribute serves to identify the file being edited while the element ID specifies the altered element.
While my example showcases a single editable area, this solution supports multiple editable regions within a single file.
On the server side, refer to the PHP code below. Please note that I'm working within a framework, so there may be differences in the syntax utilized compared to standard PHP functions:
... (remaining content similar to original response)
I recognize that regular expressions might not always be the optimal choice. For more straightforward systems, you may want to explore employing the PHP Dom Object Model instead if your HTML conforms to valid standards.
I trust this explanation proves beneficial!