コンテンツ検索 web パーツでホバーパネルを表示してみた

前回のポスト
コンテンツ検索webパーツの表示をカスタマイズする
のオマケです。

SharePoint2013では、検索結果のアイテムにカーソルをあてると詳細がホバーパネルで表示されます。
しかし、コンテンツ検索 web パーツではホバーパネルが表示されません。そこで、なんとか表示させるべくカスタマイズしてみました。

完成イメージはこちら。
20150828
ホバーパネルの表示テンプレートは、マスターページギャラリー>Display Templates>Searchフォルダの中にあります。
このうち、Item_xxx_HoverPanel.htmlというのがそれです。検索結果のファイルタイプによって、表示テンプレートが細かく分けられているのですね。
今回は、Item_Default_HoverPanel.htmlをダウンロードして使います。
ダウンロードしたItem_Default_HoverPanel.htmlを開き、中身を以下のように書き換えます。


<html xmlns:mso="urn:schemas-microsoft-com:office:office" xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882">
<head>
<title>Blog Hover Panel</title>
<!–[if gte mso 9]><xml>
<mso:CustomDocumentProperties>
<mso:TemplateHidden msdt:dt="string">0</mso:TemplateHidden>
<mso:MasterPageDescription msdt:dt="string"></mso:MasterPageDescription>
<mso:ContentTypeId msdt:dt="string">0x0101002039C03B61C64EC4A04F5361F385106603</mso:ContentTypeId>
<mso:TargetControlType msdt:dt="string">;#SearchHoverPanel;#</mso:TargetControlType>
<mso:HtmlDesignAssociated msdt:dt="string">1</mso:HtmlDesignAssociated>
<mso:ManagedPropertyMapping msdt:dt="string">'Title':'Title','AuthorOWSUSER':'AuthorOWSUSER','Path':'Path','Description':'Description','EditorOWSUSER':'EditorOWSUSER','LastModifiedTime':'LastModifiedTime','CollapsingStatus':'CollapsingStatus','DocId':'DocId','HitHighlightedSummary':'HitHighlightedSummary','HitHighlightedProperties':'HitHighlightedProperties','FileExtension':'FileExtension','ViewsLifeTime':'ViewsLifeTime','ParentLink':'ParentLink','FileType':'FileType','IsContainer':'IsContainer','SecondaryFileExtension':'SecondaryFileExtension','DisplayAuthor':'DisplayAuthor','DiscussionPost':'DiscussionPost','Created':'Created'</mso:ManagedPropertyMapping>
</mso:CustomDocumentProperties>
</xml><![endif]–>
</head>
<body>
<div id="Item_Blog_HoverPanel">
<!–#_
var postMaxLengthInChars = 500;
var i = 0;
var id = ctx.CurrentItem.id;
ctx.CurrentItem.csr_ShowViewLibrary = !Srch.U.isWebPage(ctx.CurrentItem.FileExtension);
if(ctx.CurrentItem.IsContainer)
{
ctx.CurrentItem.csr_FileType = Srch.Res.ct_Folder
}
ctx.currentItem_ShowChangedBySnippet = true;
var userPersonaId = id + "_peopleUserPersona";
var authorUsername = Srch.U.getUsernameFromAuthorField(ctx.CurrentItem.AuthorOWSUSER);
AddPostRenderCallback(ctx, function()
{
Srch.SSU.renderPersona(authorUsername, userPersonaId);
});
_#–>
<div class="ms-srch-hover-innerContainer ms-srch-hover-standardSize" id="_#= $htmlEncode(id + HP.ids.inner) =#_">
<div class="ms-srch-hover-arrowBorder" id="_#= $htmlEncode(id + HP.ids.arrowBorder) =#_"></div>
<div class="ms-srch-hover-arrow" id="_#= $htmlEncode(id + HP.ids.arrow) =#_"></div>
<div class="ms-srch-hover-content" id="_#= $htmlEncode(id + HP.ids.content) =#_" data-displaytemplate="BlogHoverPanel">
<div id="_#= $htmlEncode(id + HP.ids.header) =#_" class="ms-srch-hover-header">
_#= ctx.RenderHeader(ctx) =#_
</div>
<div id="_#= $htmlEncode(id + HP.ids.body) =#_" class="ms-srch-hover-body">
<div class="ms-srch-hover-post">
<div id="_#= $htmlEncode(userPersonaId) =#_" class="ms-srch-hover-postPersona"></div>
<div><p>
<h4>
<!–#_
var author = "";
if (!$isEmptyString(ctx.CurrentItem.AuthorOWSUSER))
{
author = Srch.U.getDisplayNameFromAuthorField(ctx.CurrentItem.AuthorOWSUSER);
}
_#–>
_#= $htmlEncode(author) =#_
</h4></p>
<div class="ms-srch-hover-text ms-srch-hover-postText">
_#= $htmlEncode(Srch.U.truncateEnd(ctx.CurrentItem.DiscussionPost, postMaxLengthInChars)) =#_
</div>
<div class="ms-metadata">
<!–#_
if(!$isNull(ctx.CurrentItem.Created))
{
var timeSincePostId = id + "_timeSincePost";
AddPostRenderCallback(ctx, function()
{
Srch.U.renderFriendlyTimeIntervalString(ctx.CurrentItem.Created, timeSincePostId);
});
_#–>
<span class="ms-srch-hover-dateMetadata" id="_#= $htmlEncode(timeSincePostId) =#_"></span>
<!–#_
}
_#–>
</div>
</div>
</div>
</div>
<div id="_#= $htmlEncode(id + HP.ids.actions) =#_" class="ms-srch-hover-actions">
_#= ctx.RenderFooter(ctx) =#_
</div>
</div>
</div>
</div>
</body>
</html>

書き換えたファイルを「Item_Blog_HoverPanel.html」とリネームして保存し、Searchフォルダにアップロードします。

次に、前回のポストで作成した「Item_BlogPost.html」をダウンロードし、以下のように書き換えます。


<html xmlns:mso="urn:schemas-microsoft-com:office:office" xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882">
<head>
<title>For Blog Post</title>
<!–[if gte mso 9]><xml>
<mso:CustomDocumentProperties>
<mso:TemplateHidden msdt:dt="string">0</mso:TemplateHidden>
<mso:ManagedPropertyMapping msdt:dt="string">'Picture URL'{画像の URL}:'PublishingImage;PictureURL;PictureThumbnailURL','Link URL'{リンクの URL}:'Path','Line 1'{行 1}:'Title','Line 2'{行 2}:'DiscussionPost','Line 3'{行 3}:'Created','Line 4'{行 4}:'AuthorOWSUSER','Line 5'{行 5}:'LikesCount', 'SecondaryFileExtension','ContentTypeId'</mso:ManagedPropertyMapping>
<mso:MasterPageDescription msdt:dt="string">このアイテム表示テンプレートでは、100 x 100 の大きさでアイテムの画像が左側に表示されます。画像の右側には、タイトル、既定アイテムの説明、カスタムの管理プロパティ用の行が表示されます。</mso:MasterPageDescription>
<mso:ContentTypeId msdt:dt="string">0x0101002039C03B61C64EC4A04F5361F385106603</mso:ContentTypeId>
<mso:TargetControlType msdt:dt="string">;#Content Web Parts;#</mso:TargetControlType>
<mso:HtmlDesignAssociated msdt:dt="string">1</mso:HtmlDesignAssociated>
</mso:CustomDocumentProperties>
</xml><![endif]–>
</head>
<body>
<!–
Warning: Do not try to add HTML to this section. Only the contents of the first <div>
inside the <body> tag will be used while executing Display Template code. Any HTML that
you add to this section will NOT become part of your Display Template.
–>
<script>
$includeLanguageScript(this.url, "~sitecollection/_catalogs/masterpage/Display Templates/Language Files/{Locale}/CustomStrings.js");
</script>
<!–
Use the div below to author your Display Template. Here are some things to keep in mind:
* Surround any JavaScript logic as shown below using a "pound underscore" (#_ … _#) token
inside a comment.
* Use the values assigned to your variables using an "underscore pound equals"
(_#= … =#_) token.
–>
<div id="Item_BlogPost">
<!–#_
var id = ctx.ClientControl.get_nextUniqueId();
var itemId = id + Srch.U.Ids.item;
var hoverId = id + Srch.U.Ids.hover;
var hoverUrl = "~sitecollection/_catalogs/masterpage/Display Templates/Search/Item_Blog_HoverPanel.js";
$setResultItem(itemId, ctx.CurrentItem);
if(ctx.CurrentItem.IsContainer){
ctx.CurrentItem.csr_Icon = Srch.U.getFolderIconUrl();
}
ctx.currentItem_ShowHoverPanelCallback = Srch.U.getShowHoverPanelCallback(itemId, hoverId, hoverUrl);
ctx.currentItem_HideHoverPanelCallback = Srch.U.getHideHoverPanelCallback();
var encodedId = $htmlEncode(ctx.ClientControl.get_nextUniqueId() + "_BlogPost_");
var linkURL = $getItemValue(ctx, "Link URL");
linkURL.overrideValueRenderer($urlHtmlEncodeValueObject);
var line1 = $getItemValue(ctx, "Line 1");
var line2 = $getItemValue(ctx, "Line 2");
var line3 = $getItemValue(ctx, "Line 3");
var line4 = $getItemValue(ctx, "Line 4");
var line5 = $getItemValue(ctx, "Line 5");
var StrLine5 = 0;
if(!line5.isEmpty){
StrLine5 = line5.value;
}
var StrLine2 = line2.value;
if (StrLine2.length > 150){
StrLine2 = StrLine2.substr(0, 150) + "…";
}
var pictureURL = $getItemValue(ctx, "Picture URL");
var pictureId = encodedId + "picture";
var pictureMarkup = Srch.ContentBySearch.getPictureMarkup(pictureURL, 100, 100, ctx.CurrentItem, "cbs-picture3LinesImg", line1, pictureId);
line1.overrideValueRenderer($contentLineText);
line2.overrideValueRenderer($contentLineText);
line3.overrideValueRenderer($contentLineText);
line4.overrideValueRenderer($contentLineText);
line5.overrideValueRenderer($contentLineText);
var containerId = encodedId + "container";
var pictureLinkId = encodedId + "pictureLink";
var pictureContainerId = encodedId + "pictureContainer";
var dataContainerId = encodedId + "dataContainer";
var line1LinkId = encodedId + "line1Link";
var line1Id = encodedId + "line1";
var line2Id = encodedId + "line2";
var line3Id = encodedId + "line3";
var line4Id = encodedId + "line4";
var line5Id = encodedId + "line5";
var dataDisplayTemplateTitle = "BlogPost";
_#–>
<div class="cbs-picture3LinesContainer ms-srch-item" id="_#= $htmlEncode(itemId) =#_" onmouseover="_#= ctx.currentItem_ShowHoverPanelCallback =#_" onmouseout="_#= ctx.currentItem_HideHoverPanelCallback =#_" data-displaytemplate="_#= $htmlEncode(dataDisplayTemplateTitle) =#_">
<div id="_#= $htmlEncode(hoverId) =#_" class="ms-srch-hover-outerContainer"></div>
<div class="cbs-picture3LinesImageContainer" id="_#= pictureContainerId =#_">
<!–#_
if(!linkURL.isEmpty)
{
_#–>
<a class="cbs-pictureImgLink" href="_#= linkURL =#_" title="_#= $htmlEncode(line1.defaultValueRenderer(line1)) =#_" id="_#= pictureLinkId =#_">
<!–#_
}
_#–>
_#= pictureMarkup =#_
<!–#_
if(!linkURL.isEmpty)
{
_#–>
</a>
<!–#_
}
_#–>
</div>
<div class="cbs-picture3LinesDataContainer" id="_#= dataContainerId =#_">
<div style="overflow:hidden">
<a class="cbs-picture3LinesLine1Link" href="_#= linkURL =#_" title="_#= $htmlEncode(line1.defaultValueRenderer(line1)) =#_" id="_#= line1LinkId =#_" style="display:block">
<h4 class="cbs-picture3LinesLine1 ms-accentText2 ms-noWrap" id="_#= line1Id =#_"> _#= line1 =#_</h4>
</a>
<span class="cbs-picture3LinesLine4 ms-textSmall ms-noWrap" id="_#= line4Id =#_" style="float:right;">Posted By _#= line4 =#_</span>
</div>
<!–#_
if(!line2.isEmpty)
{
_#–>
<div class="cbs-picture3LinesLine2" style="height:auto;" id="_#= line2Id =#_" > _#= StrLine2 =#_ </div>
<!–#_
}
_#–>
<div style="overflow:hidden;">
<!–#_
if(!line3.isEmpty)
{
_#–>
<span class="cbs-picture3LinesLine3 ms-textSmall ms-noWrap" id="_#= line3Id =#_" style="float:left;">[Posted : _#= line3 =#_]</span>
<span class="cbs-picture3LinesLine5 ms-textSmall ms-noWrap" id="_#= line5Id =#_" style="float:right;">Likes Count : _#= StrLine5 =#_</span>
<!–#_
}
_#–>
</div>
<div>
<a class="cbs-button1" href="_#= linkURL =#_" style="float:right;">Read More</a>
</div>
</div>
</div>
</div>
</body>
</html>

書き換えたItem_BlogPost.htmlを、Content Web Partsフォルダにアップロードします。
以上です!
もし、カスタマイズが反映されない場合はコンテンツ検索webパーツの表示テンプレートで「For Blog Post」をえらびなおし、プロパティのマッピングで以下のように選択しなおしてみてください。
20150828-2

なお、カスタマイズにあたってはこちらの記事を参考にしました。
The SharepointWallah: Sharepoint 2013 Search – Adding a hover panel to a content search webpart display template.
C/D/H Talks Tech » Custom Hover Panel on the Content Search Web Part using a Custom Display Template

若干、無理やりな感じもありますが・・・参考になればうれしいです。

コンテンツ検索webパーツの表示をカスタマイズする

だいぶ前になりますが、コンテンツ検索webパーツでブログの新着を表示するやり方を紹介しました。
【2013】コンテンツ検索 webパーツでBlogの新着情報を表示する | Me & SharePoint.

今回の記事と、次回の記事
コンテンツ検索 web パーツでホバーパネルを表示してみた
はその続きとなります。

前回のままではタイトルとサムネイルだけでさびしいので、本文の一部、投稿日、それから「Read More」ボタンを表示してみたいと思います。
完成イメージです。
20150826

これを実現するには、「表示テンプレート」というものをカスタマイズします。
表示テンプレートのカスタマイズについては、MSのサポートチームのブログで詳しく紹介されていますので参考にしてください。
SharePoint 2013 お知らせアイテムを新着順に表示するコンテンツ検索 Web パーツを作成する – Japan SharePoint Support Team Blog – Site Home – TechNet Blogs.
SharePoint 2013 検索結果の表示を制御する表示テンプレート – Japan SharePoint Support Team Blog – Site Home – TechNet Blogs.

さて、マスターページギャラリーからDisplay Templates>Content Web Parts とフォルダをたどって、Item_Picture3Lines.htmlをダウンロードします。
ダウンロードしたテンプレートを「Item_BlogPost.html」とリネームします。
テンプレートを開き、以下のように書き換えます。

<html xmlns:mso="urn:schemas-microsoft-com:office:office" xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"> 
<head>
<title>For Blog Post</title>

<!--[if gte mso 9]><xml>
<mso:CustomDocumentProperties>
<mso:TemplateHidden msdt:dt="string">0</mso:TemplateHidden>
<mso:ManagedPropertyMapping msdt:dt="string">'Picture URL'{画像の URL}:'PublishingImage;PictureURL;PictureThumbnailURL','Link URL'{リンクの URL}:'Path','Line 1'{行 1}:'Title','Line 2'{行 2}:'DiscussionPost','Line 3'{行 3}:'Created', 'SecondaryFileExtension','ContentTypeId'</mso:ManagedPropertyMapping>
<mso:MasterPageDescription msdt:dt="string">このアイテム表示テンプレートでは、100 x 100 の大きさでアイテムの画像が左側に表示されます。画像の右側には、タイトル、既定アイテムの説明、カスタムの管理プロパティ用の行が表示されます。</mso:MasterPageDescription>
<mso:ContentTypeId msdt:dt="string">0x0101002039C03B61C64EC4A04F5361F385106603</mso:ContentTypeId>
<mso:TargetControlType msdt:dt="string">;#Content Web Parts;#</mso:TargetControlType>
<mso:HtmlDesignAssociated msdt:dt="string">1</mso:HtmlDesignAssociated>
</mso:CustomDocumentProperties>
</xml><![endif]-->
</head>

<body>

    <!--
            Warning: Do not try to add HTML to this section. Only the contents of the first <div>
            inside the <body> tag will be used while executing Display Template code. Any HTML that
            you add to this section will NOT become part of your Display Template.
    -->
    <script>
        $includeLanguageScript(this.url, "~sitecollection/_catalogs/masterpage/Display Templates/Language Files/{Locale}/CustomStrings.js");
    </script>

    <!--
        Use the div below to author your Display Template. Here are some things to keep in mind:
        * Surround any JavaScript logic as shown below using a "pound underscore" (#_ ... _#) token
        inside a comment.

        * Use the values assigned to your variables using an "underscore pound equals"
        (_#= ... =#_) token.
    -->

    <div id="Item_BlogPost">

<!--#_

var encodedId = $htmlEncode(ctx.ClientControl.get_nextUniqueId() + "_BlogPost_");

var linkURL = $getItemValue(ctx, "Link URL");
linkURL.overrideValueRenderer($urlHtmlEncodeValueObject);

var line1 = $getItemValue(ctx, "Line 1");
var line2 = $getItemValue(ctx, "Line 2");
var line3 = $getItemValue(ctx, "Line 3");

var StrLine2 = line2.value;
if (StrLine2.length > 150){
    StrLine2 = StrLine2.substr(0, 150) + "...";
}

var pictureURL = $getItemValue(ctx, "Picture URL");
var pictureId = encodedId + "picture";
var pictureMarkup = Srch.ContentBySearch.getPictureMarkup(pictureURL, 100, 100, ctx.CurrentItem, "cbs-picture3LinesImg", line1, pictureId);

line1.overrideValueRenderer($contentLineText);
line2.overrideValueRenderer($contentLineText);
line3.overrideValueRenderer($contentLineText);

var containerId = encodedId + "container";
var pictureLinkId = encodedId + "pictureLink";
var pictureContainerId = encodedId + "pictureContainer";
var dataContainerId = encodedId + "dataContainer";
var line1LinkId = encodedId + "line1Link";
var line1Id = encodedId + "line1";
var line2Id = encodedId + "line2";
var line3Id = encodedId + "line3";

var dataDisplayTemplateTitle = "BlogPost";

 _#-->
        <div class="cbs-picture3LinesContainer" id="_#= containerId =#_" data-displaytemplate="_#= $htmlEncode(dataDisplayTemplateTitle) =#_">
            <div class="cbs-picture3LinesImageContainer" id="_#= pictureContainerId =#_">
<!--#_
if(!linkURL.isEmpty)
{
_#-->
                <a class="cbs-pictureImgLink" href="_#= linkURL =#_" title="_#= $htmlEncode(line1.defaultValueRenderer(line1)) =#_" id="_#= pictureLinkId =#_">
<!--#_
}
_#-->
                    _#= pictureMarkup =#_
<!--#_
if(!linkURL.isEmpty)
{
_#-->
                </a>
<!--#_
}
_#-->
            </div>
            <div class="cbs-picture3LinesDataContainer" id="_#= dataContainerId =#_">
                <a class="cbs-picture3LinesLine1Link" href="_#= linkURL =#_" title="_#= $htmlEncode(line1.defaultValueRenderer(line1)) =#_" id="_#= line1LinkId =#_">
                    <h4 class="cbs-picture3LinesLine1 ms-accentText2 ms-noWrap" id="_#= line1Id =#_"> _#= line1 =#_</h4>
                </a>
<!--#_
if(!line2.isEmpty)
{
_#-->
                <div class="cbs-picture3LinesLine2" style="height:auto;" id="_#= line2Id =#_" > _#= StrLine2 =#_ </div>
<!--#_
}
_#-->
                <div style="overflow:hidden;">
<!--#_
if(!line3.isEmpty)
{
_#--> 
                    <span class="cbs-picture3LinesLine3 ms-textSmall ms-noWrap" id="_#= line3Id =#_" style="float:left;">[Posted : _#= line3 =#_ ]</span>
<!--#_
}
_#-->
                    <a class="cbs-button1" href="_#= linkURL =#_" style="float:right;">Read More</a>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

書き換えたItem_BlogPost.htmlを、ダウンロード元のフォルダにアップロードし、タイトルに「For Blog Post」と入力して保存します。

コンテンツ検索webパーツを設置したページに戻り、webパーツを編集状態にします。
「表示テンプレート」セクションの「アイテム」で、先ほどテンプレートのタイトルに設定した「For Blog Post」を選択します。

20150826-2

もし、うまく内容が反映されない場合は「プロパティのマッピング」でデフォルトで入力されているプロパティを再度選択しなおしてから保存してみてください。

最後に、「Read More」のリンクをボタン状にし、全体の見栄えを整えるためのCSSをページに埋め込みます。
ページを編集状態にし、「スクリプトエディター」を挿入して、コードスニペットのに以下のコードを貼り付けて保存します。

<style>
.cbs-picture3LinesContainer {
    padding: 20px 0;
    margin: 5px;
}
.cbs-picture3LinesImageContainer {
    margin-top: 5px;
}
.cbs-button1{
    text-decoration: none;
    text-align: center;
    display: inline-block;
    background-color: #59b1eb;
    border: 2px solid #59b1eb;
    color: #fff;
    padding: 0 30px;
}
.cbs-button1:visited{
    color: #fff;
}
.cbs-button1:hover {
    background-color: #fff;
    border-color: #59b1eb;
    color: #59b1eb;
    text-decoration: none;
}
.cbs-button1::before,
.cbs-button1::after {
    position: absolute;
    z-index: -1;
    display: block;
    content: '';
}
.cbs-button1,
.cbs-button1::before,
.cbs-button1::after {
    box-sizing: border-box;
    transition: all .3s;
}
</style>

これでOKです!
おなじみのコンテンツクエリwebパーツよりは、xslスタイルシートをいじらなくて済む分カスタマイズのハードルは低いですよね。
これからどんどん使っていきたいと思います!

SharePointサイトをレスポンシブ・デザインにするときの情報源

こんにちは。世間は夏休み真っ盛りですが、私は絶賛仕事中です!!
電車が空いててうれしいぞ!!!

さて、ここのところSharePointサイトをモバイルでも美しく表示できるようにするべく、いろいろと実験していたのですがそのとき参考にした情報を備忘録として載せておきます。

基本的な前提と方針は、
・バージョンはSharePoint2013
・SharePoint Onlineへのマイグレーションも見据え、カスタムマスタページは作らない
(参考:Latest Advice on Office 365 Branding | Microsoft Trends.)
・よって、デバイスチャネルも使わず、レスポンシブデザインで設計
・とはいえ、JavaScriptは使いたいのでマスタページでのJavaScriptの参照は(しぶしぶ)許容する
といったところです。

デフォルトマスタページを使い、CSSだけで何とかするやり方はもうほぼこれでOKではないかと。
Making seattle.master Responsive | Our SharePoint Experience.

レスポンシブなCSSグリッド・システムを導入するやり方。まだ試してないけど、そのうちやってみたいと思います。
Apply grid system to SharePoint using SUSY | Stefan Bauer – n8d

マスタページをいじくらずにviewportを設定する裏ワザ。
Add viewport meta without editing the master page | Stefan Bauer – n8d.

グローバルナビゲーションをモバイルではアコーディオンメニューにしたい!
巷にあふれるプラグインをしつこくいろいろ試した結果これがよさそうです。
レスポンシブメニューを作成できるjQueryプラグイン「MeanMenu」 | たすデザイン.
具体的な導入方法は、いずれ別のエントリで書きます。

JavaScript内でユーザーエージェントを判別したいとき。
2015年版JavaScriptユーザエージェント判別・判定.

viewportの設定になやんだら?
もう逃げない。HTMLのviewportをちゃんと理解する – Qiita.

マスタページをいじくらずともサイト全体にカスタムJavaScriptを適用するにはこんなやり方もあるです。
JavaScript を使用して SharePoint サイト UI をカスタマイズする.
MSの推奨はたぶんこれ。私はまだ試してないです。アドイン作れとか言われると、とたんにハードルが・・・(汗)

新たにいい情報が出てきたら、今後も追加していく予定です。
また、こんなのも参考になるよ!なんてのがあったらTwitterでもなんでもお知らせください。

コンテンツクエリ webパーツでアイテムをダイアログで開く

社内ポータルをSharePointでつくっている場合、コンテンツクエリwebパーツ(cqwp)でサイトコレクション内のお知らせを集約してトップページに表示・・・なんてことはよくやりますよね。

で、cqwpだと、ふつうアイテムのタイトルをクリックすると、同一ウィンドウ内でクリックしたアイテムの表示画面へ遷移していきます。
これを、PCで表示したときはダイアログで開き、モバイルで表示したときは同一画面内で遷移するようにカスタマイズしてみます。
PCでの表示イメージはこんな感じ。
20150708

さて、cqwpのカスタマイズに関しては、Microsoft MVP山崎さん執筆の以下の良記事がありますので、まだコンテンツクエリwebパーツいじったことない・・・という方はまずご一読ください。
若干古い記事ですが、2013となった今でも十分通用する内容で、cqwpをカスタマイズしよう!なんて場面ではもはやバイブルといってよいと思います。
コンテンツ クエリ Web パーツ (1.複数サイトから「お知らせ」を取得する) – SharePoint Technical Notes.
コンテンツ クエリ Web パーツ (2.今日の日付を表示する) – SharePoint Technical Notes.
コンテンツ クエリ Web パーツ (3.更新日時と本文を取得する) – SharePoint Technical Notes.
コンテンツ クエリ Web パーツ (4.本文から不要なタグを削除する) – SharePoint Technical Notes.
コンテンツ クエリ Web パーツ (5.表示部分を整える) – SharePoint Technical Notes.
コンテンツ クエリ Web パーツ (6.リンク機能を修正する) – SharePoint Technical Notes.
コンテンツ クエリ Web パーツ (7.任意の列で並び替える) – SharePoint Technical Notes.
コンテンツ クエリ Web パーツ (8.タスクの一覧を取得する) – SharePoint Technical Notes.

では、上記の記事をひととおり眺めていただいた、という前提で・・・
おもむろにソースコードです。

ItemStyle.xslの、コンテンツクエリwebパーツで使いたいスタイルの「<div class=”link-item”>」のaタグ部分を以下のように書き換えます。

<div class="link-item">
    <xsl:call-template name="OuterTemplate.CallPresenceStatusIconTemplate"/>
    <!--<a href="{$SafeLinkUrl}" title="{@LinkToolTip}">-->
    <a onmouseover="javascript:this.style.cursor='pointer';" onclick="OpenModalDialog('{$SafeLinkUrl}','{$DisplayTitle}')"  title="{@LinkToolTip}">
        <xsl:if test="$ItemsHaveStreams = 'True'">
            <xsl:attribute name="onclick">
                <xsl:value-of select="@OnClickForWebRendering"/>
            </xsl:attribute>
        </xsl:if>
        <xsl:if test="$ItemsHaveStreams != 'True' and @OpenInNewWindow = 'True'">
            <xsl:attribute name="onclick">
                <xsl:value-of disable-output-escaping="yes" select="$OnClickTargetAttribute"/>
            </xsl:attribute>
        </xsl:if>
        <xsl:value-of select="$DisplayTitle"/>
    </a>
    <div class="description">
        <xsl:value-of select="@Description" />
    </div>
</div>

※ItemStyle.xslを編集したら、忘れずに発行しましょう。

次に、コンテンツクエリwebパーツを配置したページに、スクリプトエディタで以下のJavaScriptを埋め込みます。

<script>
function OpenModalDialog(url, title) {
    if (navigator.userAgent.search(/iPhone/) != -1 || navigator.userAgent.search(/iPad/) != -1 || navigator.userAgent.search(/iPod/) != -1 || navigator.userAgent.search(/Android/) != -1) {
        location.href = url;
        return false;
    }
    var options = { title: title, url: url };
    SP.UI.ModalDialog.showModalDialog(options);
}
</script>

以上でOKです!
検証したのはSharePoint2013ですが、使っている手法は2010のころからあるものばかりなので、2010でも動くと思います。
(2010の場合は、スクリプトを外部ファイルにして、コンテンツエディタwebパーツでページにリンクしてください。)

上で紹介したcqwpのカスタマイズと組み合わせれば、ちょっとcqwpで作ったとは思えないパーツに仕上がりそうですね。

SharePointのページに下部固定のフッターをつけてみた

SharePointのページにフッターをつけたい場合、通常はマスタページをカスタマイズすることになると思います。
しかし、マスタページをいじれないエンドユーザー・デベロッパーとか、SharePoint Onlineでカスタムマスタページを作りたくない!という場合はちょっと工夫が必要となります。

以下で紹介するのは、JavaScriptでフッター要素をページに追加し、CSSでスタイリングする方法です。
ページのコンテンツが少ない場合はウィンドウの最下部、それ以外はページ最下部に固定で表示されます。
検証した環境はSharePoint2013オンプレミスのチームサイト、ブラウザがIE11、マスタページはデフォルトのseattle.masterです。

できあがりはこんな感じ。
20150624

ソースコードです。

<style>
#s4-bodyContainer {
    position:relative;
    min-height: 100%;
    padding-bottom: 30px;
    box-sizing: border-box;
}
/* footer */
.footer-container{
    position:absolute;
    bottom: 0;
    left: 0;
    text-align: center;
    width: 100%;
    padding: 5px;
    background-color:#29629C;
    color: #fff;
    box-sizing: border-box;
    overflow: hidden;
}
</style>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    var footerHtml = "<div class='footer-container ms-dialogHidden'>";
    footerHtml += "<footer>© Marineko. All rights reserved.</footer></div>";
    $("#s4-bodyContainer").append(footerHtml);
});
</script>

マスタページはさわりたくないんだよね~、というときに、参考にしてみていただければと思います。

REST APIでログインユーザー情報を取得し、フォームに表示する

SharePoint2013のお話です。

SharePointのフォームにログインユーザーの情報をデフォルト値として設定したいというのはよくある要望だと思います。

私も過去にいくつかポストしてきましたし、
列に現在のユーザー名を表示【2010】 | Me & SharePoint.
列に現在のユーザー名を表示【2013】 | Me & SharePoint.

CSOMでユーザー情報を取得するやり方については、いっつもお世話になっているMVP 太田さんのブログにくわしい解説があります。
ログインしているユーザーのプロファイルを JavaScript で取得する | idea.toString();.

まあ、上の記事だけでも十分なんですが、試しにREST APIを使って実装してみましたのでメモとして残しておきます。

新規フォームの「投稿者」というユーザー列にログインユーザーの表示名、「所属」という一行テキスト列に所属名を表示します。

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        SP.SOD.executeFunc('sp.js', 'SP.ClientContext', SetCurrentUserInfo);
    });

    function SetCurrentUserInfo() {
        $.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties",
            contentType: "application/json;odata=verbose",
            headers: { "accept": "application/json;odata=verbose" },
            success: onSuccess,
            error: onError
        });
    }

    function onSuccess(data, request) {
        // アカウント名
        var loginName = data.d.AccountName;
        // 表示名
        var dispName = data.d.DisplayName;
        // 所属情報
        var arr = data.d.UserProfileProperties.results;
        var dept;
        for (var i = 0, len = arr.length; i < len; i++) {
            if (arr[i].Key == "Department") {
                dept = arr[i].Value;
            }
        }

        //PeoplePickerに設定
        var PeoplePickerId = $("div[title='投稿者']").attr('id');
        var PeoplePickerInput = $("input[title='投稿者']");
        PeoplePickerInput.val(dispName);
        var PeoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[PeoplePickerId];
        PeoplePicker.AddUnresolvedUserFromEditor(true);

        //所属を設定
        $("input[title='所属']").val(dept);

    }

    function onError(error) {
        console.log(error);
    }
</script>

こちらのコードを、NewForm.aspxにスクリプトエディタで埋め込めばOKです!
コード的にはCSOMのほうがシンプルなように思いますが、もしRESTを使いたいシチュエーションがあったとき、参考にしていただけるとうれしいです。

サイドリンクバーをアコーディオンメニューにする

前回に引き続き、SharePoint2013のサイドリンクバーのプチカスタマイズです。

サイドリンクバーもエントリ数や第2階層のリンクがふえてくると、画面から見切れてしまうことがあります。
そんなとき、第1階層でアコーディオンで開閉可能にできるといいですよね。

で、jQueryを使ってサイドリンクバーをアコーディオンにする以下のポストを見つけ、
Simple Expand/Collapse for the Quick Launch in SharePoint 2013 or SharePoint Online | Marc D Anderson’s Blog.

これでOK!と思ってたんですが、このコードだとサイドリンクバーのエントリをクリックして他ページに遷移すると、開閉状態がチャラになって全部閉じてしまうという・・・
ちょっと使い勝手がよくないです。

そこで、クッキーで開閉状態を覚えさせるようにしてみました。
クッキーの操作には、jquery.cookie.jsというプラグインを使用しています。

※jquery.cookie.jsの使い方などはこちらをご参考に・・・
jquery.cookie.jsの使い方と簡単なサンプルを紹介します|Webpark.

ソースコードです。

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<style>
.ms-core-listMenu-verticalBox li > span.menu-item {
    cursor: pointer;
}
</style>
<script>
$(document).ready(function(){
    var topLevelLinks = $("div[id$='QuickLaunchMenu'] > ul > li:has('ul') > span, div[id$='QuickLaunchMenu'] > ul > li:has('ul') > a");
    topLevelLinks.prepend("<span class='accordion'><i class='fa fa-caret-right'></i></span>");
    topLevelLinks.closest("li").find("> ul").hide();

    var idx = 0;
    var key;
    topLevelLinks.each(function () {
        key = "expandable" + idx;
        $(this).attr("id", key);
        if ($.cookie(key) == "open") {
            $(this).closest("li").find("> ul").show();
            $(this).find(".accordion").replaceWith("<span class='accordion'><i class='fa fa-caret-down'></i></span>");
        }
        idx = idx + 1;
    });

    topLevelLinks.click(function(e) {
        e.preventDefault();
        var childUl = $(this).closest("li").find("> ul");
        var isVisible = childUl.is(":visible");        
        if(isVisible) {  
            $(this).find(".accordion").replaceWith("<span class='accordion'><i class='fa fa-caret-right'></i></span>");
            childUl.slideUp();
            $.cookie($(this).attr('id'), "close", { path: '/' });
        } else {
            $(this).find(".accordion").replaceWith("<span class='accordion'><i class='fa fa-caret-down'></i></span>");
            childUl.slideDown();
            $.cookie($(this).attr('id'), "open", { path: '/' });
        }
    });
});
</script>

上記のコードを、スクリプトエディタでページに埋め込みます。
できあがりはこんな感じ。
20150608

参考にしていただけるとうれしいです♪

サイドリンクバーにwebフォントでリストマークをつける

SharePoint3分クッキングの時間がやってまいりましたー。
と、いうわけで、またしても3分でできる小ネタをご紹介します。
(SharePoint2013のオンプレ環境、ブラウザはIE11で検証しました)

サイドリンクバーのエントリに、好きなリストマークをつけたい!と思い立っても、画像を準備して表示させるのは結構面倒です。やる気が失せがちです。
そんなとき、webフォントでさくっとリストマークを表示できれば便利ですよね。

というので、定番webアイコンフォント Font Awesome を利用してリストマークをつけてみました。

できあがりはこんな感じです。
20150513

なお、Font Awesomeの基本的な使い方などは、以下をご参考に。
アイコンをWebフォントで表示! Font Awesomeの使い方 [ホームページ作成] All About.

CSSです。

@import "//netdna.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.css";

.ms-core-listMenu-verticalBox > ul > li:first-child .ms-core-listMenu-item::before {
    content: "\f015";
    font-family: FontAwesome;
    margin-right: 5px;
    width:1em;
}

.ms-core-listMenu-verticalBox ul li ul li .ms-core-listMenu-item::before {
    content: "\f101";
    font-family: FontAwesome;
    margin-right: 3px;
    width:1em;
}

こういうちょっとしたことでも、サイトの雰囲気はずいぶん変わるので、気が向いたときに試してみていただければと思います。

SharePoint2013 注目リンクを丸くしてみた

SharePoint 3分クッキング!ということで、3分でできるカスタマイズをご紹介します。

先日、注目リンクのカスタマイズについての記事をアップしましたが、その続き(?)です。

表題のとおりで、ふつうは四角い注目リンクを、CSSで丸くしてみよう!というものです。
できあがりはこんな感じ。
20150515

CSSです。

.ms-tileview-tile-content, .ms-tileview-tile-content img {
    height: 150px;
    border-radius: 50%;
}
.ms-tileview-tile-detailsListMedium {
    padding: 10px 40px;
}

いい加減なCSSなんで、キャプションの文字列が若干切れてますが、そこはご愛嬌ということで(笑)。
サイトの雰囲気をやわらかくしたいときに、いかがでしょうか?

SharePointのナビゲーションで「最近使った項目」を隠す

GWはひどい鼻風邪で引きこもっていたにもかかわらず、いまだに風邪が抜けません。ずぴー。やれやれ。

前回のポストで、ちょろっとふれたナビゲーションの「最近使った項目」。
図1
これ、表示したくないって時も結構あるんでないかと思います。

しかしながら、2010の時みたいにCSSで隠すのはちょっと難しい(クラス名とか、IDとかついてないのですよ・・・)。
仕方ないので奥の手・JavaScriptで無理やり隠します。

$(document).ready(function() {
    $(".ms-core-listMenu-item:contains('最近使った項目')").parent().hide();
});

コード見ていただければわかりますが表面的に隠しているだけですので、気がむいたときにサイトの設定のナビゲーションから削除してあげたほうがいいと思います。

ついでに、2010から引き続きwikiページライブラリに出てきてしまう例のアレ
図2
も、JavaScriptで隠せます。

$(".ms-core-listMenu-item:contains('更新済みのページ')").parent().hide();
$(".ms-core-listMenu-separatorLine").hide();

サイトカスタマイズの参考になれば・・・。