Zend\Filter\PregReplace
,但实际上是preg_replace('/( {2,})(\R)/m',$2)
的包装。 我知道有人问过这个问题(Python Markdown nl2br extension等,但是这些答案都没有为我做。
我想渲染降价,以便在<p>
元素内发生的换行符将被渲染为<br>
。示例:他们键入
Here is line one.
And line two.
New paragraph.
应渲染为
<p>Here is line one.<br>And line two.</p>
<p>New paragraph.</p>
我知道,如果需要,您应该在要输入<br>
的行的末尾键入两个空格。我正在尝试这样做,以便我的用户不必这样做,而是输入文本,就好像他们在使用打字机一样(对于那些知道那是什么的人)。一份辛苦的回报,换行;有两个辛苦的回报,新的段落。
我一直在使用https://parsedown.org/,并且还尝试过https://commonmark.thephpleague.com;还有带有nl2br扩展名的Python markdown模块(逐字尝试示例,对我不起作用)。无论我做什么,最终都会导致换行过多或不足,具体取决于。
我尝试了我认为巧妙而优雅的方法:用<p>
(也尝试过white-space: "pre"
)来设置我的Markdown的pre-line
。这是可行的,除非用户使用两个空格“正确”完成了该操作,在这种情况下,您会得到不需要的double <br>
效果。
也尝试过nl2br($markdown)
,结果同样不可靠。
我希望非技术用户能够尽可能轻松地使用一些基本格式,降价似乎只是事情,但这是细节。我不想编写CMS来解决此问题。例如,我曾想过在实体上添加布尔markdown
属性,然后让他们选择yadda yadda ...不想去那里。我已经考虑过在数据库写入时或在渲染之前进行一些字符串替换或正则表达式魔术。但是再次,希望避免变得太复杂。 (要使其更具挑战性,我还必须导入几千条非降价的旧记录,并可能处理旧旧记录之间的问题。)
也许我正在忽略一个简单而明智的出路。对最佳策略有何想法?
Update:
受普遍需求,无法正常工作的代码示例。这是一个Zend MVC应用程序,涉及我称为MOTD和MOTW的学说实体(M消息O f T他D ay和M消息<< O > f T he W eek);这些具有称为内容的字符串属性。通常,我将这些实体视为Note
,并且它们实现了NoteInterface
。当我从数据库中检索这些内容时(通过内部使用自定义Doctrine存储库类的NotesService
类),是时候在控制器将其分配给视图之前将内容呈现为markdown了:// from NotesService.php
use Parsedown;
// stuff omitted...
/**
* gets MOT(D|W) by date
*
* @param DateTime $date
* @param string $type
* @param boolean $render_markdown
* @return NoteInterface|null
*/
public function getNoteByDate(DateTime $date, string $type, bool $render_markdown = true) :? NoteInterface
{
$entity = $this->getRepository()->findByDate($date,$type);
if ($entity && $render_markdown) {
$content = $entity->getContent();
$entity->setContent($this->parsedown($content));
}
return $entity;
}
布尔值$render_markdown
的点用于当我们想要原始降价时,即,当它要填充表单的textarea元素时。和
parsedown()
方法,很简单:
public function parsedown(string $content) : string
{
if (! $this->parseDown) {
$this->parseDown = new Parsedown();
}
// nope...
// return nl2br($this->parseDown->text($content));
return $this->parseDown->text($content);
}
例如,在视图脚本内,我就去了
if ($this->notes['motd']): // echo nl2br($this->notes['motd']->getContent()); echo $this->notes['motd']->getContent(); else: ?><p class="font-italic no-note">no MOTD for this date</p><?php endif;
现在,如果他们以编辑形式输入内容:
here is a line and here is another now, new paragraph.
然后我们将其保存在数据库中,当您选择它并通过$ parsedown-> text($ content)运行它时,将获得以下HTML:
<p>here is a line and here is another</p> <p>now, new paragraph.</p>
请注意,上面的示例输入在换行符之前没有任何空格字符。是的,当您在换行符前键入两个空格时,效果很好。但我认为我的用户不想考虑这一点。因此,使用nl2br()
会有所帮助,除非它导致HTML中连续的<br>
过多。[我的最新想法是,使用CSS解决方案和一个输入过滤器,该输入过滤器在行尾剥去
<space><space>
。当它起作用时,我会将故事添加到我的回忆录中。 :-)
我知道有人问过这个问题(Python Markdown nl2br扩展名,等等),但是这些答案都没有为我做。我想渲染markdown以便在[
Zend\Filter\PregReplace
,但实际上是preg_replace('/( {2,})(\R)/m',$2)
的包装。 ((2)使用CSS使换行符像<br>
一样显示我的实体,例如
#motd .card-body p { white-space: pre-line }
似乎为我工作。
Zend\Filter\PregReplace
,但实际上是preg_replace('/( {2,})(\R)/m',$2)
的包装。